FAQ Database Discussion Community


Combine 2 plots (ggplot) into one plot and differenciate them

r,ggplot2
I have a problem similar to the following example. I want to differentiate the lines from different group; for example, I want distinguish the "m" sexe cdf from group 1 and the "m" sexe cdf from group 2. library(ggplot2) sexe <- rep(c("m", "w", "x"), 50) weight1 <- runif(150, 30, 90)...

making a choropleth from SpatialPolygonsDataFrame- ggplot vs ggplot2 vs plot?

r,plot,ggplot2
I have a shapefile, specifically, a SpatialPolygonsDataFrame, called cdtract. that contains one variable for each district called varcount. varcount is either "NA" or 1. When I do plot(cdtract) ...I see the map printed out but I don't see the tracts that are '1' in varcount marked any differently from those...

Multiple line diagrams in the same ggplot

r,ggplot2
I am creating a line diagrams from this data. Does anybody know how to add another line (with a second set of recall and precision points) in the same diagram? recall11Point = c(0.2, 0.2, 0.4, 0.4, 0.4, 0.6, 0.6, 0.6, 0.8, 1.0) precision11Point = c(1.0, 0.5, 0.67, 0.5, 0.4, 0.5,0.43,0.38,0.44,0.5)...

R shiny ggplot2 error 'Results must be all atomic, or all data frames'

r,ggplot2,shiny,shinyapps
I get inconsistent errors with my shiny app and I can't seem to figure out what is wrong. This is the most common error. Error: Results must be all atomic, or all data frames. The shiny app basically allows the user to chose 1 or more files, then reads those...

Plotting discrete count data as “staple” of points in ggplot2

r,plot,ggplot2
My goal is, to plot how often some bands have played at a festival. Basically, the plot should look like this: ggplot(plot.df2, aes(reorder(bands,count),count)) + geom_point() + coord_flip()+ theme_bw() But i would like to have a point for every time, the band has played there. This would be a "staple of...

Align text right justified but center of each box in geom_text

r,ggplot2,geom-text
I have created a graph with ggplot using geom_tile and geom_text. I want to be able to read the numbers down one column and have them all lineup. I set the font to Courier and used hjust to justify the numbers (otherwise the negative sign throws off the alignment). However...

R, ggplot2, facetted histogram, decending order, factor x-axis labels

r,ggplot2,order,facet
I have an interesting problem where I need to produce a facetted histogram series which I want to put in decending order for each panel. This below code replicates the problem. library(ggplot2) set.seed(1) nGroup = 10; nSample = 10 df <- data.frame(Group=rep(1:nSample,nGroup), Category = factor(sample(LETTERS, nGroup*nSample, replace=TRUE), levels=LETTERS), Amount =...

Limit the color variation in R using scale_color_grey

r,colors,ggplot2
Before I start, allow me to explain my graph: I have two Genotypes (WTB and whd) and each have two conditions (0 and 7), so I have four lines. Now, I want to make a plot where each variable and its condition is the same color. Anything with whd will...

ggplot2: can't sort x axis by y value

r,sorting,ggplot2
I have problem in sorting x axis by y value in ggplot2: here is the code below #Data hp=read.csv(textConnection( "class,year,amount a,99,100 a,100,200 a,101,150 b,100,50 b,101,100 c,102,70 c,102,80 c,103,90 c,104,50 d,102,90")) hp$year=as.factor(hp$year) #Plotting p=ggplot(data=hp) p+geom_bar(binwidth=0.5,stat="identity")+ # aes(x=reorder(class,amount),y=amount,label=amount,fill=year)+ theme() Here is the result: How do I sort my x axis by a...

Grouped barplot in ggplot2 in R

r,ggplot2,bar-chart
I would like to make a grouped bar plot. An example of my data is as follows: site code year month gear total value 678490 2012 3 GL 13882 678490 2012 4 GL 50942 678490 2012 5 GL 54973 678490 2012 6 GL 63938 678490 2012 7 GL 23825 678490...

Combine base and ggplot graphics in R figure window in different pages

r,pdf,plot,ggplot2
I used this solution to combine an R plot and ggplot and then used it in a loop to print a of these to a pdf in different pages. But for some reason the margins get bigger in every new page and at some point plots disappear. How can I...

Assign Specific Colors to Specific Values [duplicate]

r,ggplot2
This question already has an answer here: How to assign colors to categorical variables in ggplot2 that have stable mapping? 4 answers I ask R to make a series of plots. However, the colors assigned to the different variables by ggplot2 vary depending on the actual data. I need...

Overriding panel.grid in ggplot2

r,ggplot2
The following code first drops the X-axis text, and then adds it back in with a red color: p_text <- qplot(data = mtcars, x = hp, y = disp) + theme(axis.text.x = element_blank()) p_text + theme(axis.text.x = element_text(colour = "red")) Similarly, one would expect this code to do the same...

qplot - legend text in italics

r,ggplot2
I have created a plot: p = qplot(distance, Recombination, data = forplot, colour = factor(Species), size=I(4)) p + labs(title="Effective Recombination", x="Distance Categories", y="Effective Recombination Ratio", colour="Species") + ylim(0,0.022) However, I need the legend names (s. mimosarum and s. africanus) to be in italics. How do I do that? I have...

R: ggplot2: Unable to plot points from a data.frame

r,plot,ggplot2
So I want to do a simple plot where the following x-coordinates should be plotted as points. This is what my data.frame looks like: gap_pos 1 50646312 2 50647076 3 50647511 4 50647512 5 50647513 6 50647546 Now I have tried to do it as simple as possible: gap_plot <-...

How to plot a lagged time series?

r,ggplot2
I am trying to draw some quick graphs for exploratory analysis and have the following question: How can I plot a lagged time series in ggplot? I am trying to do something like this: ggplot(data,aes(x=xdata,y=xdata-1)+geom_point() But xdata-1 is subtracting 1 from xdata instead of reading the previous xdata value. ggplot...

Equal distance among all points on an axis

r,ggplot2,scatter-plot
I am trying to plot a simple scatter plot like this: The minimal code I am using for generating this plot is as follows: ggplot(fig1c, aes(x=xvar, y=yvar)) + scale_x_log10(breaks=unique(fig1c$xvar)) + scale_y_continuous(breaks=seq(0, 10, by=1), labels=as.character(seq(0, 10, by=1))) + geom_point(aes(fill=Method, color=Method, shape=Method), size = 5, guides=FALSE) + scale_colour_brewer(palette="Set1") + geom_line(aes(fill=Method, color=Method)) +...

ggbiplot: how to maintain group colors after changing point size?

r,ggplot2,ggbiplot
I am doing a PCA on plots in 2 habitat types in which I collected data on multiple environmental variables. I was able to change the colors of the points from the ggbiplot defaults. I want the size of each point to depend on canopy cover in that plot, and...

geom_bar define border color with different fill colors

r,ggplot2
I want to draw a bar plot with geom_bar where I want unique fill colors surrounded by a black border. However the instruction color="black" is not interpreted as "black" as I want it to be and I get red borders. library(ggplot2) test=as.data.frame(cbind(a=c(1,1,2,3), b=1:4, c=as.character(1:4))) ggplot(test) + geom_bar(aes(x=a, y=b, fill=c, colour="black"),...

How to set x-axis with decreasing power values in equal sizes

r,plot,ggplot2,cdf
Currently I am doing some cumulative distribution plot using R and I tried to set x-axis with decreasing power values (such as 10000,1000,100,10,1) in equal sizes but I failed: n<-ceiling(max(test)) qplot(1:n, ecdf(test)(1:n), geom="point",xlab="check-ins", ylab="Pr(X>=x)")+ geom_step() +scale_x_reverse(breaks=c(10000,1000,100,10,1)) +scale_shape_manual(values=c(15,19)) It seems that the output has large interval for 10000, then all the...

R: Plot Density Graph for data in tables with respect to Labels in tables

r,plot,ggplot2
I got a data in table form which look like this in R: V1 V2 1 19 -1539 2 7 -1507 3 3 -1446 4 7 -1427 5 8 -1401 6 2 -422 7 22 4178 8 5 4277 9 10 4303 10 18 4431 ....200 million more lines to...

ggplot: aesthetics from variable string without aes_string

r,ggplot2,lazy-evaluation
i have a variable v containing a data.frame column name. I now want to plot it against its index. Normally, plotting a column against its index is easy: df <- data.frame(a = c(.4, .5, .2)) ggplot(df, aes(seq_along(a), a)) + geom_point() But in my case, I can’t figure out what incantations...

geom_vlines multiple vlines per plot

r,ggplot2,time-series,timeserieschart
How can I get ggplot to produce something similar like library(ggplot2) library(reshape2) library(ecp) synthetic_control.data <- read.table("/path/synthetic_control.data.txt", quote="\"", comment.char="") n <- 2 s <- sample(1:100, n) idx <- c(s, 100+s, 200+s, 300+s, 400+s, 500+s) sample2 <- synthetic_control.data[idx,] df = as.data.frame(t(as.matrix(sample2))) #calculate the change points changeP <- e.divisive(as.matrix(df[1]), k=8, R = 400,...

combined use of geom_boxplot and scale_x_datetime

r,ggplot2
I want to use geom_boxplot and rescale my axis with scale_x_datetime at the same time. However geom_boxplot requires a factor as an input, while scale_x_datetime will only accept class POSIXct. Here is a reproducible example: library(ggplot2) library(scales) dates <- c("02/27/92", "02/27/92") times <- c("20:03:20", "22:29:56") x <- paste(dates, times) x...

splitting or removing graphs after arrangeGrob

r,ggplot2,gridextra
I created a graph with ggplot and later I used arrangeGrob to combine those graphs. Is there a way to remove parts a graph from this combined plot? Or maybe extract? Here is a minimal example: library(ggplot2) library(gridExtra) df <- data.frame(x=rnorm(20), y=rnorm(20), y2=rnorm(20)) g1 <- ggplot(df, aes(x, y)) + geom_point()...

How do I draw a better quality graph for this example using R ggplot() function? [closed]

r,ggplot2,data.frame
I have a data frame, that comprises of three Categorical and one Continuous variable and I have converted into long format using melt and it is as shown below. data_long <- structure(list(Year = c(2010L, 2010L, 2010L, 2011L, 2011L, 2011L, 2012L, 2012L, 2012L, 2012L, 2013L, 2013L, 2013L, 2014L, 2014L, 2014L, 2010L,...

How to modify ggplot2 scater plot

r,ggplot2
Here is my sample dataset: df1 = data.frame(Count.amp = c(8,8,1,2,2,5,8), Count.amp.1 = c(4,4,2,3,2,5,4)) I tried library(ggplot2) qplot(Count.amp,Count.amp.1, data=df1) Is there any ways to plot in such a way that the size of the dot is proportional to the number of elements in each dots?...

How can I use stat_smooth to show one line, on a two factor figure?

r,ggplot2
I have a data.frame as such: df <- data.frame(a = runif(1000), b = runif(1000), c = runif(1000), d = sample(c("yes", "no"), 1000, replace=TRUE)) And I ran a logistic regression: lm <- glm(data = df, factor(d) ~ a + b + c, family = binomial) Produced the predicted probabilities: df$pred <-...

Plotting in R 3.1.2 [closed]

r,plot,ggplot2,ggmap
I have records of data by account (say unique 400 records). Each record has three different indications indicated premium. For each record, I am concerned with how the indications compare to each other. In some cases, the indications may be all relatively in line, while in other the 3 indications...

Making multiple plots with mapply

r,ggplot2,mapply
I made the following dataframe df: V1 <- 1:10 V2 <- 11:20 V3 <- 21:30 V4 <- 31:40 df <- data.frame(V1,V2,V3,V4) I also made a function which should make a simple scatterplot based on the arguments var1 and var2. ScatterPlot <- function(var1, var2) { ggplot(data = df, aes(x = var1,...

R Biplot with clusters as colors

r,ggplot2,pca
I'm doing a clustering after a PCA transformation and I would like to visualize the results of the clustering in the first two or three dimensions of the PCA space as well as the contribution from the original axes to the projected PCA ones. I use the factoextra library which...

Conditionally change ggplot facet background with date axis

r,ggplot2,facet
Using facet_grid with ggplot, I'm trying to conditionally change the background of some the panels, to highlight ones of interest I've identified. I'm trying to achieve this following the answer from a similar question here. I understand the idea is to plot a geom_rect layer with opacity first to act...

Subgroup Boxplots in R

r,ggplot2,visualization
I'm trying to make a graphic that will show three things side-by-side. First is to show change in the individual over time. Next is to show change in their peer group over time. Last is to show change in the overall population over time. I have four time points on...

ggplot + facet: dropping factors with no data

r,ggplot2
Let's say I have the following data: z <- structure(list(EVTYPE = c("AAA", "BBB", "CCC", "DDD", "ZZZ", "WWW", "AAA", "BBB", "CCC", "DDD", "ZZZ", "WWW"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("ZOMBIES", "PLANTS"), class = "factor"), value = c(354, 765, 389, 321,...

Scatterplot of Year-On-Year Correlation of Data in R using ggplot2

r,plot,ggplot2
I have some yearly football data that I would like to test to see if certain team metrics are repeatable in the next year. My data is in a data.frame and looks something like this: y2003 y2004 y2005 Team 1 51.95455 51.00000 53.59091 Team 2 54.18182 56.31818 49.09091 Team 3...

Issue with geom_text when using position_dodge

r,ggplot2
I saw this answer but couldn't replicate it. I get my data like this: df = data.frame(x = rep(sample(letters, 4), 2), y = round(runif(8,1,100),0), z = c(rep("group1",4), rep("group2",4))) # I then add a 'percent' column like so: df$perc[1:4] = df$y[1:4] / sum(df$y[1:4]) df$perc[5:8] = df$y[5:8] / sum(df$y[5:8]) # Which I...

How to stack error bars in a stacked histogram using geom_errorbar , ggplot?

r,ggplot2
I want to stack the error bars in a stacked histogram using geom_errorbar / ggplot. In my ggplot statement, I have tried to used both position="stack" and position="identity". None of them worked. Here is my ggplot statement: ggplot(DF, aes(x=factor(year), y=proportion, fill=response)) + facet_grid(. ~ sex) + theme(legend.position="none") geom_bar(position="stack", stat="identity") +...

ggplot2 heatmap scaling row

r,ggplot2
I am trying to make a heatmap. I have a csv file that has a list of samples, and data at numerous timepoints. So it looks like this Sample 1h 2h 3h 4h 5h 6h 7h Test1 Test2 except much bigger and obviously filled with data. My goal is to...

Reorder X variable based on Facet variable

r,ggplot2,facet
I'm creating a facet grid. I'm attempting to reverse the order of levels on the x-axis (Context) based on the level of the specified facet variable(.~Order). (E.g., For Order, if "NFF", then order of Context = "NF", "IF"; if "IFF", then order of Context = "IF", "NF"). Edit Data I'm...

Shiny + GGplot - mouse click coordinates

ggplot2,shiny,rstudio
I have a doubt in shiny ploting a GGPlot Bar Graph. I can recognize coordinates of mouse click (x,y), but I need know a value of bar (x-axis) to refresh the graph with parameter and simulate a drill-down. Anyone can help me? library(shiny) library(ggplot2) ui <- fluidPage( plotOutput("plot", click =...

Fitting a polinomial curve to time series data

r,ggplot2,time-series,lm
I have a time series graph with monthly article frequency as the y axis. The data looks like this: Count.V Date Month Week Year 2637 6 2006-01-02 2006-01-01 2006-01-02 2006-01-01 406 4 2006-01-03 2006-01-01 2006-01-02 2006-01-01 543 4 2006-01-04 2006-01-01 2006-01-02 2006-01-01 998 3 2006-01-05 2006-01-01 2006-01-02 2006-01-01 1400 4...

R ggplot2 boxplot not properly shown when knitting html

r,ggplot2,boxplot
tried a simply boxplot with ggplo2 ggplot(aes(x = quality, y = residual.sugar),data=data)+ geom_boxplot(fill="#9999CC")+scale_y_continuous(limits =c (0,20)) when i exucute it in R itself, it looks like want it , like this: but when i knit it to get my html file, it looks like this : Anyone knows how to fix...

Plot quantiles of distribution in ggplot2 with facets

r,ggplot2,quantile,density-plot
I'm currently plotting a number of different distributions of first differences from a number of regression models in ggplot. To facilitate interpretation of the differences, I want to mark the 2.5% and the 97.5% percentile of each distribution. Since I will be doing quite a few plots, and because the...

How to deal with ggplot2 and overlapping labels on a discrete axis

r,plot,ggplot2,axis-labels
ggplot2 does not seem to have a built-in way of dealing with overplotting for text on scatter plots. However, I have a different situation where the labels are those on a discrete axis and I'm wondering if someone here has a better solution than what I've been doing. Some example...

ggplot2 and first data point in a line

r,ggplot2,facet
I am creating two plots using ggplot2 and then using grid.arrange to merge them together. I should say that both of the plots are also using facet_grid for a visual tweaking. My problem is that the bottom plot, which is really a data table, ends up being "cut off" on...

how to get x axis to intercept y at non-zero position with ggplot2?

r,ggplot2
I have a plot of temperatures: qplot( TS, TEMPERATURE, data=dataInput(), geom="bar", stat="identity", fill=TEMPERATURE) + labs(x="Measurement date", y="Temperature (degrees C)") + ggtitle("temperature") However, what I would like to do is have the x axis intercept the y axis at 50 degrees C so that values below 50 degrees are drawn downwards....

Adding partial horizontal lines with ggplot2 in R

r,ggplot2
I have the following data: mydf = read.table(text=" name a b x 10 15 y 20 25 z 35 45 ", header = T) I want to create a plot as follows: I am not able to add horizontal lines from points to the vertical line at x=50. These lines...

Plotting pre-computed statistics on POSIX dates with ggplot's geom_boxplot

r,ggplot2,data.table,lubridate
I'm trying to create a series of boxplots showing a distribution of date values. I compute the quantiles using data.table, then I feed them to ggplot to be plotted. When I try to plot them, however, I get an error that says "Error: '/' not defined for "POSIXt" objects". Here's...

Strange performance of multi qplots to a figure in R when parameter of qplot includes list

r,ggplot2
Aim: save multi qplots into a figure. The point is there is a list parameter to loop (see code. It's more clear!). The output is different as I expected. They are the same! # Make y be a list containing different values. y <- list() for (j in 1:6) {...

Extracting data from TraMineR for use in other plotting packages (e.g. ggplot2)

r,ggplot2,traminer
I am writing a paper using TraMineR for sequence plotting and ggplot for the remaining graphs. I would like to extract the data that seqIplot( ) uses to create index plots and use it to make an index plot using geom_tile( ), for the sake of maintaining the same visual...

Dodge points in point char with ggplot2

r,ggplot2
Given the data.table: df = data.table(type=rep(letters[1:3], each=2), count=c(1, 1, 4, 4, 4, 4), year=rep(c('2013', '2014'), 3)) type count year a 1 2013 a 1 2014 b 4 2013 b 4 2014 c 4 2013 c 4 2014 I tried to plot the point chart and line chart to show the...

Scaling Time in Hours in ggplot2

r,ggplot2
In the following plot I wanted to remove the date and keep the time in hours. I have seen few solutions like here and another where Time is converted to numeric. I liked the use of require(scales) ggplot(data= dfweek2, aes(x = Time, y = Mean_steps)) + facet_grid(day ~.) + geom_path()...

Draw geom_smooth only for fits that are significant

r,ggplot2,statistics
How can I make ggplot plot geom_smooth(method="lm"), but only if it fits some criteria? For instance, if I only want to draw lines if the slope is statistically significant (i.e. p from the lm fit is less than 0.01). EDIT: Updated to a more complex example involving facets. Instead of...

R: custom ggplot2 color-transform gives error in labels

r,ggplot2,colortransform
Basically, i have a dataframe with 3 numeric vectors(x,y,z), and lets say i wanna make a scatter plot of x,y colored by z. I want to transform the colorscale with a squareroot that respects sign, so i made my own with trans_new. Here is a simple dataset, but with the...

How to add inbetween space in nested boxplots ggplot2

r,ggplot2,boxplot
I would like to added a marginal space between groups of box plots by using the stats_summary method. Here is a small example of my problem library(ggplot2) library(reshape2) data1 <- (lapply(letters[1:5], function(l1) return(matrix(rt(5*3, 1), nrow = 5, ncol = 3, dimnames = list(cat2=letters[6:10], cat3=letters[11:13]))))) names(data1) <- letters[1:5] data2 <- melt(data1)...

Plotting (ggplot) numeric values from mixed long format column of class character

r,ggplot2,dplyr,tidyr
Following the tidy data standard, I have my data in long format with a key and a value column. The values for some keys are numeric, for others are characters, and so R has the entire column set as character class. When I use filter() to pipe only the numeric...

R: melting a data.frame to use in ggplot2 for multiple y-value plot

r,plot,ggplot2,melt
I would like to plot multiple Y-values against a time-variable. I don't have a complete data frame, as I didn't collect all the Y-values to start with. I believe I need to melt() the data frame before passing it to ggplot2, but that seems to fail because the "id" column...

Group values that occur only once into an OTHER field

r,ggplot2
I've got a collection of Roman Coins that I'm trying to represent using ggplot in R. There are 25 different denominations in the data, but I'd like to merge together all denominations that only have one occurrence into an 'OTHER' field, so that the graphs are easier to read. Medium...

How do I add a legend in ggplot2 using R?

r,ggplot2
I have been searching around the internet for an answer to my question, but so far all I've found is people who ask the same question, but have different circumstances then me. Most people have two or more data sets on their ggplot and are adding a legend to show...

showing different units in each free_y of facet_grid

r,ggplot2,facet-wrap
I have plotted two facets one on top of the other with two different ys (a percentage and a cost) and the same x (Years). I took most of the ideas from this post and some variations of the same. I'd like to show the labels of the y axis...

Create abbreviated legends manually for long X labels in ggplot2

r,ggplot2,legend
I would like to create a simple bar chart with ggplot2 and my problem is that my x variable contains long strings so the labels are overlaid. Here are fake datas and the plot : library(dplyr) library(tidyr) library(ggplot2) set.seed(42) datas <- data.frame(label = sprintf("aLongLabel%d", 1:8), ok = sample(seq(0, 1, by...

Plotting with ggplot through calling another function

r,ggplot2
I have a function which gets a matrix with 4 columns as input. This function plots boxplots using two columns of input matrix, fills them with different color based on third column and also plots points on each box based on fourth column to show some parameters. p1 <- ggplot(pl1,...

How to execute .r files to output figures?

r,ggplot2
I really need serious help here. I have been working with R the last month. I have been analyzing data, and plotting many visualizations using ggplot2. I have many .r files which includes data transformations and reading .csv ..etc My instructor wants me to show him my code or at...

Ploting the world map in R

r,ggplot2
I am trying to visualize some data from countries in a world map using R and ggplot2. I am using the following code(sample): WorldData <- map_data('world') df <-data.frame(region=c('Hungary','Lithuania','Argentina'),value=c(4,10,11)) Total <- merge(WorldData,df,by='region') and for ploting using ggplot: p <- ggplot() p <- p + geom_polygon(data=Total, aes(x=long, y=lat, group = group,fill=Total$value),colour="white") +...

Plotting a step function with only horizontal lines

r,ggplot2
I use ggplot2 to plot a step function using geom_step(). What I need now is to get rid of the vertical lines. This should be a quite common problem in math at least... The docs do not mention such possibility . Is there a hidden argument somewhere, or do I...

Overlaying jittered points on boxplot conditioned by a factor using ggplot2

r,ggplot2,overlay,boxplot,jitter
I am making a boxplot conditioned by a factor similar to this example: p <- ggplot(mtcars, aes(factor(cyl), mpg)) p + geom_boxplot(aes(fill = factor(am))) There are few points in the data set, and I'd like to express this visually by overlaying the data points. I want to overlay the points colored...

error with lapply on anonymous ggplot function

r,plot,ggplot2
I'm trying to use lapply on an ggplot anonymous function if (inputMethodP=="WITHINFILE") { par(mfrow=c(5,listPortions)) plotList<-lapply(RangeStatResultP, function(listPart) { ggplot(matrixPart, aes(x = factor(Var2), y=value)) + geom_violin()+ ggtitle(names(listPart)+xlab(listnum)+ylab("Coverage")+ stat_summary(fun.y = median, geom = "point", position = position_dodge(width = .9), size = 6, shape = 4, show_guide = F) }) } when ever I...

Cannot produce ggplot2 in Shiny

r,ggplot2,shiny,ecdf
Below is my code. I am able to produce the ecdf plots in R studio but not when i put it all together in a shiny app like I have below: Server.R library(shiny) library(ggplot2) shinyServer(function(input, output) { datasetInput <- reactive({ mydf = data.frame( a = rnorm(100, 0, 1), b =...

Plotting multivariate time-series data in R

r,graph,plot,ggplot2,time-series
My data looks like this: > head(Full.df) Date Month Week Year Count.S Count.G Count.W Count.F 1 2006-01-02 2006-01-01 2006-01-02 2006-01-01 0 7 9 6 2 2006-01-03 2006-01-01 2006-01-02 2006-01-01 0 13 12 4 3 2006-01-04 2006-01-01 2006-01-02 2006-01-01 0 13 15 4 4 2006-01-05 2006-01-01 2006-01-02 2006-01-01 0 20 6...

Creating new shape palettes in ggplot2 and other R graphics

r,graphics,ggplot2
I'd like to specify my own shape palettes for ggplot2 at least as a vector for input into scale_shape_manual. I really like the paired shapes palette from JMP, but noticed R doesn't have some of these shapes. In particular, sideways triangles (e.g. |> or <|) or a filled upside down...

How to make a Pareto chart (aka rank-order chart) with ggplot2

r,ggplot2
I found the rank-order chart (also known as Pareto chart) in the book "Data Analysis with Open Source Tools" quite useful. So I tried to plot the example in the book with ggplot2. The following figure is given in the book, note that the coordinates is flipped such that the...

ggplot Bar Plot semantics

python,ggplot2,python-ggplot
I am trying to use ggplot in Python for the first time and the semantics are completely unobvious to me. I have a pandas dataframe with two columns: date and entries_sum. What I would like to do is plot a bar plot with the date column as each entry on...

How to produce legend in ggplot by mapping aes_string from different data frames in ggplot?

r,function,ggplot2
I am trying to create a legend for ggplot density that compares one group to all groups. Using this example - R: Custom Legend for Multiple Layer ggplot - I can do this successfully with code below. met1 <- data.frame( Score = sample(1:10), Group = sample(c("Group1", "Group2", "Group3"), 30, replace...

stuck making a data frame after using street2coordinates (R)

r,google-maps,ggplot2
I am trying to follow the tutorial outlined here but having trouble But I am running into a problem at this step: my_crime <- data.frame(year=my_crime$Year, community=my_crime$Community.Area, type=my_crime$Primary.Type, arrest=my_crime$Arrest, latitude=my_crime$Latitude, longitude=my_crime$Longitude) My equivalent step is: geocode <- data.frame(latitude=geocode$lat, longitude=geocode$long) I get the following error: Error in geocode$lat : $ operator is...

ggplot2 & facet_wrap - eliminate vertical distance between facets

r,ggplot2
I'm working with some data that I want to display as a nxn grid of plots. Edit: To be more clear, there's 21 categories in my data. I want to facet by category, and have those 21 plots in a 5 x 5 square grid (where the orphan is by...

Set categorical axis labels with scales “free” ggplot2

r,plot,ggplot2,facet
I am trying to set the labels on a categorical axis within a faceted plot using the ggplot2 package (1.0.1) in R (3.1.1) with scales="free". If I plot without manually setting the axis tick labels they appear correctly (first plot), but when I try to set the labels (second plot)...

R: ggplot2: plot initiating at the axes

r,ggplot2
I'm trying to respond to a reviewer that wants some changes to a figure... I am using ggplot2 to generate Kaplan-Meier curves, and the reviewer wants the X-axis to start at 0. The default in ggkmTable adds some space between 0 and the Y-axis. I can't figure out what to...

ggplot2 shapes by variables with replicates [duplicate]

r,ggplot2,shapes
This question already has an answer here: Changing shapes used for scale_shape() in ggplot2 3 answers I have the table that I attach in the Excel in Dropbox I want to make a plot with three basic colours (black, red and blue) by Country and the shapes (e.g., 24,...

Assign same custom color to two lines coming from different data-frames but in the same plot

r,plot,ggplot2
I have the following plot, plotting data coming from two different data-frames: ggplot() + stat_summary( data = d0_400, aes(x=number, y=(1-value), shape=as.factor(0), size=1 ) , fun.y=mean, geom="line" ) + stat_summary( data = d0_400, aes(x=number, y=(1-value), shape=as.factor(0), size=4 ) , fun.y=mean, geom="point" ) + stat_summary( data = d1_400, aes(x=number, y=(1-value), shape=as.factor(1), size=1...

Setting limits with scale_x_datetime and time data

r,ggplot2,time-series
I want to set bounds for the x-axis for a plot of time-series data which features only time (no dates). My limits are: lims <- strptime(c("03:00","16:00"), format = "%H:%M") And my ggplot prints fine, but when I add this to scale_x_datetime scale_x_datetime(limits = lims) I get Error: Invalid input: time_trans...

replacing NAs by value but excluding from geom_smooth

r,ggplot2
I am trying to make a scatter plot and also plot a regression line for my data. Before plotting, I want to have the NAs replaced by a fixed number to get all points in my graph and since they are all on one line, they are easily visible... But...

R language: how to use ggplot2 to plot multiple vectors on one graph with regression lines?

r,ggplot2
If I have the following data frame (DF) for example, how to use ggplot2 to graph VAR1 versus year, and VAR2 versus year, in one graph? And add regression lines? year VAR1 VAR2 2001 10 12 2002 30 12 2003 20 15 I can get one graph using qplot(year, VAR,...

skip the empty dataframes and produce the output

r,merge,ggplot2,tidyr,rpostgresql
sessionInfo() R version 3.2.0 (2015-04-16) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build 7601) Service Pack 1 locale: [1] LC_COLLATE=German_Germany.1252 LC_CTYPE=German_Germany.1252 [3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C [5] LC_TIME=German_Germany.1252 attached base packages: [1] grid stats graphics grDevices utils datasets methods [8] base other attached packages: [1] WriteXLS_3.5.1 tidyr_0.2.0 scales_0.2.4 gridExtra_0.9.1 [5]...

ggplot format italic annotation

r,ggplot2
Can I use markup in a ggplot annotation? Let's say, I have this graph: p <- function(i) 8*i a <- function(i) 1+4*i*(i-1) library(ggplot2) library(reshape2) i <- 1:(8*365/7) d <- data.frame(i=i,p=p(i),a=sapply(i,a)) d <- melt(d, id.vars='i') p <- ggplot(d, aes(i, value, linetype=variable)) + geom_hline(yintercept=700^2) + geom_line() + scale_linetype_manual(values=c(2,1)) + #geom_point() + scale_x_continuous(breaks=(0:20)*365/7,...

geom_rect() main variable not found

r,ggplot2
I want to plot rectangle "shading" in with my ggplot. The ggplot code works and provides the image shown below. I looked for information here and constructed a data frame for the x and y values. mydf<-data.frame(tiempo=df5$tiempo,vel=df5$TR2x45.17)[1:14,] structure(list(tiempo = c(618.2, 618.4, 618.6, 618.8, 619, 619.2, 619.4, 619.6, 619.8, 620, 620.2,...

Adjust space between gridded, same-sized ggplot2 figures

r,ggplot2,gridextra
I am attempting to arrange multiple ggplot2 plots into one output/grid. I'd like the plots (without considering the labels) to be the same size. I have found a way to do this, but now I'd like to adjust the space between the plots. For example: In this plot, I'd like...

Why is my graph's Y-axis not in the right order?

r,ggplot2
I am trying to plot a graph for a data frame that looks like this: year week cases 2003 1 0 2003 2 0 2003 3 12 2003 4 23 2003 5 12 2003 6 16 2003 7 20 2003 8 13 2003 9 0 2003 10 0 2003 11...

Error with facet_wrap since updating ggplot2 to 1.0.1

r,ggplot2
I have a code snipped which worked fine since last week when I updated ggplot2 from 0.9.3 to 1.0.1. So basically here is a reproducible example: df <- data.frame(values=rnorm(200000), title=rep(seq(1,20), each=10000)) ggplot(df, aes(values)) + geom_histogram(binwidth=.08) + facet_wrap(~ title) ggplot(df, aes(values)) + geom_histogram(binwidth=.05) + facet_wrap(~ title) In version 0.9.3 it worked...

Dynamically create expression for ggplot legend?

r,ggplot2,expression,legend
I want to plot a line graph, with multiple lines, coloured depending on a grouping variable. Now I want to set the legend labels via scale-command: scale_color_manual(values = colors_values, labels = ...) The legend labels are as following: "x^2", "x^3", "x^4" etc., where the range is dynamically created. I would...

Log Scale Transformation in R for ggplot2

r,ggplot2
I am working on a problem set for ggplot2 in R. One of my questions asks for a scale log transformation, which both my notes and the Hadley Wickam book say can be done through this function: scale_x_log() However, when I use this function, R does not recognize it. Any...

How to customize lines in ggpairs [GGally]

r,ggplot2,ggally
I have the following plot: Generated with this code: library("GGally") data(iris) ggpairs(iris[, 1:4], lower=list(continuous="smooth", params=c(colour="blue")), diag=list(continuous="bar", params=c(colour="blue")), upper=list(params=list(corSize=6)), axisLabels='show') My questions are: How can I change the correlation line to be red, now it's black. And the correlation line is buried under the scatter plot. I want to put it...

Why can I not get the x axis labels to show in my graph?

r,ggplot2
This is the data (in not the most readable form): id bfi stress alcohol stroop condition 1 4239 Open 0 0 2 N 2 71538 Extra 1 0 0 N 3 8855 Con 0 1 0 N 4 558 Agree 3 0 0 N 5 23 Agree 23 1 0...

How do I put multiple boxplots in the same graph in R?

r,plot,ggplot2,rstudio,boxplot
Sorry I don't have example code for this question. All I want to know is if it is possible to create multiple side-by-side boxplots in R representing different columns/variables within my data frame. Each boxplot would also only represent a single variable--I would like to set the y-scale to a...

Sequence index plots in ggplot2 using geom_tile( )

r,ggplot2,traminer
I'm trying to use ggplot to create sequence plots, for the sake of keeping the same visual style within my paper using sequence analysis. I do: library(ggplot2) library(TraMineR) library(dplyr) library(tidyr) data(mvad) mvad_seq<-seqdef(mvad,15:length(mvad)) mvad_trate<-seqsubm(mvad_seq,method="TRATE") mvad_dist<-seqdist(mvad_seq,method="OM",sm=mvad_trate) cluster<-cutree(hclust(d=as.dist(mvad_dist),method="ward.D2"),k=6) mvad$cluster<-cluster...

R using ggplot2: “Error in value == ”primary“ : comparison is not allowed for expressions”

r,ggplot2,facet
I am attempting to change the labels in the handy facet plot available in R with ggplot using a function that I created, facet_labeller: #This function will map a new name to the category labels facet_labeller <- function(var, value){ value <- as.character(value) # Creates labels with superscript for 1st and...

R ggplot : Can't change y-axis scale range with facetted plot

r,ggplot2,facet
I have a simple problem but I can't figure out why it won't work -> I can't adjust the y scale range on my faceted bar plot: # Data # df<-as.data.frame(c("x","y","z","x","y","z","x","y","z","x","y","z")) colnames(df)<-"x" df$y<-c(10,15,20,5,25,45,10,10,20,40,20,5) df$facet<-c(1,1,1,1,1,1,2,2,2,2,2,2) df$group<-c("A","A","A","B","B","B","A","A","A","B","B","B") # Plot # ggplot(df, aes(x=x, y=y, fill=group)) + facet_grid( ~ facet) + scale_fill_manual(values=c("blue", "red")) +...

Only show last four labels on bar graph

r,ggplot2
My code here produces a bar graph with labels on each bar of the y value. I would like to only show the last 4 data points as the labels. What is the best way to do it? library(data.table) library(ggplot2) df <- data.table(x= c(1,2,3,4,5,6,7,8,9,10), y=c(4,1,-3,-5,4,1,2,4,2,-3)) ggplot(df, aes(x=x, y=y)) + geom_bar(stat="identity")...

ggplot equivalent for matplot

r,ggplot2
Is there an equivalent in ggplot2 to plot this dataset? I use matplot, and read that qplot could be used, but it really does not work. ggplot/matplot data<-rbind(c(6,16,25), c(1,4,7), c(NA, 1,2), c(NA, NA, 1)) as.data.frame(data) matplot(data, log="y",type='b', pch=1) ...

How to put several formulas outside of a plot (top) using ggplot2?

r,plot,ggplot2
I have problems using annotation_custom. Here is the dataset: DOSE PROD pH 1 0 CL 4.3550 2 0 CO 4.3250 3 0 CZ 4.1475 4 0 PF 4.2300 5 0 RP 4.1225 6 25 CL 4.3420 7 25 CO 4.3520 8 25 CZ 4.7840 9 25 PF 4.2640 10 25...

ggplot reorder stacked bar plot based on values in data frame

r,ggplot2,bar-chart,stacked-chart
I am making stacked bar plots with ggplot2 in R with specific bar ordering about the y-axis. # create reproducible data library(ggplot2) d <- read.csv(text='Day,Location,Length,Amount 1,4,3,1.1 1,3,1,2 1,2,3,4 1,1,3,5 2,0,0,0 3,3,3,1.8 3,2,1,3.54 3,1,3,1.1',header=T) ggplot(d, aes(x = Day, y = Length)) + geom_bar(aes(fill = Amount, order = Location), stat = "identity")...