Menu
  • HOME
  • TAGS

ggplot reorder stacked bar plot based on values in data frame

r,ggplot2,bar-chart,stacked-chart

Try: ggplot(d, aes(x = Day, y = Length)) + geom_bar(aes(fill = Amount, order = -Location), stat = "identity") Notice how I swapped rev with -. Using rev does something very different: it stacks by the value for each row you happen to get if you reverse the order of values...

ggplot Bar Plot semantics

python,ggplot2,python-ggplot

How about: ggplot(aes(x='date', y='entries_sum'), data=data) + geom_bar(stat='identity') ...

Plotting a step function with only horizontal lines

r,ggplot2

Read through this example. You may want to remove the vline and play with the various parameters -- see http://docs.ggplot2.org/current/. library(ggplot2) df <- data.frame(x=seq(0, 10), y=cumsum(rnorm(11))) df$xend <- c(df$x[2:nrow(df)], NA) df$yend <- df$y p <- (ggplot(df, aes(x=x, y=y, xend=xend, yend=yend)) + geom_vline(aes(xintercept=x), linetype=2, color="grey") + geom_point() + # Solid points...

R: custom ggplot2 color-transform gives error in labels

r,ggplot2,colortransform

There is a vectorized if, called ifelse. It also seems you are missing an extra minus. super_trans <- function() { trans_new('super', function(x) ifelse(x>0, x^0.5, -(-x)^0.5), function(x) ifelse(x>0, x^2, -(-x)^2)) } ...

Multiple line diagrams in the same ggplot

r,ggplot2

d = data.frame( "Recall" = c(0.2, 0.2, 0.4, 0.4, 0.4, 0.6, 0.6, 0.6, 0.8, 1.0) , "Precision" = c(1.0, 0.5, 0.67, 0.5, 0.4, 0.5,0.43,0.38,0.44,0.5) , "Recall2" = seq(0,0.9, by = 0.1) , "Precision2" = seq(0,0.9, by = 0.1) ) library(ggplot2) ggplot(data=d) + geom_line(aes(x=Recall, y=Precision), size=1, colour="red") + geom_point(aes(x=Recall, y=Precision), size=5,...

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

r,ggplot2,shiny,shinyapps

It seems to be a problem with plyr, which is probably going to get fixed in the next R update. Until then you can fix it following these steps: Install platform specific development tools: Windows: Download and install Rtools33.exe from http://cran.r-project.org/bin/windows/Rtools/ Ubuntu or Debian based Linux: sudo apt-get install r-base-devel...

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

r,ggplot2,facet

You need to add a limits argument in your scale_y_continuous : scale_y_continuous("%", limits=c(0,50), breaks=seq(0, 50, 10), minor_breaks=seq(0,50,5), expand = c(0, 0)) Otherwise you just define the breaks position, not the axis values range....

geom_vlines multiple vlines per plot

r,ggplot2,time-series,timeserieschart

This is the solution: library(ggplot2) library(reshape2) library(ecp) synthetic_control.data <- read.table("/Users/geoHeil/Dropbox/6.Semester/BachelorThesis/rResearch/data/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, alpha = 2, min.size = 3)...

ggplot2: can't sort x axis by y value

r,sorting,ggplot2

You need to give reorder the sum function, otherwise it defaults to using the mean function. Then, I put a - in front of amount to get the order reversed. p=ggplot(data=hp) p+geom_bar(binwidth=0.5,stat="identity")+ # aes(x=reorder(class,-amount,sum),y=amount,label=amount,fill=year)+ theme() ...

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

r,ggplot2

Try removing the breaks argument to scale_x_discrete: f + ggtitle("Alcohol Usage by Personality Trait")+ labs(x="Personality Trait", y="Alcohol Usage")+ scale_x_discrete( # breaks=c("open","extra","con","agree"), labels=c("Openness","Extraversion","Conscientiousness","Agreeableness") ) + theme( plot.title=element_text(size=15,face="bold",vjust=.5), axis.title.x=element_text(size=12,face="bold",vjust=-.25), axis.title.y=element_text(size=12,face="bold",vjust=1), axis.text.x=element_text(size=10,face="bold",color="black"),...

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

r,ggplot2,data.frame

While I agree this question is too broad, here is a quick redoing of the plot that looks quite a bit better than what you had and can hopefully give you a push towards deciding how you want to present your information. A few points and suggestions: Your labels are...

Reorder X variable based on Facet variable

r,ggplot2,facet

You could do this by creating a dummy variable that is the interaction between the variable on the x-axis and the variable you are faceting by, library(ggplot2) ## Use a subset of the diamonds dataset data(diamonds) dat <- droplevels(with(diamonds, diamonds[color %in% c("E","I") & clarity %in% c("SI2", "SI1"), ])) ## See...

How do I add a legend in ggplot2 using R?

r,ggplot2

Ditch your whole long ifelse monstrosity and just modify the ggplot call to be: ggplot(p04_NoNegative, aes(x=Distance.Traveled, y=GS_ReelRaiseLowerAngle)) + geom_line(aes(color=GS_Field),size=1.1) + ggtitle("p04 entire field") + ylim(0,0.6) + ylab("Reel Height (angle)")+ xlab("Distance (m)") + scale_x_continuous(breaks = x_axis_ef) + coord_cartesian(xlim = c(0,5000)) You can set the colors via scale_color_manual (assuming GS_Field is a...

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

r,ggplot2

You just have to hack the scale labels. library(ggplot2) # fake data my_dat <- data.frame(x=1:(24*3), temp=sample(0:100, 24*3)) # the initial plot ggplot(my_dat, aes(x=x, y=temp, fill=temp)) + geom_bar(stat='identity') # make a copy my_dat2 <- my_dat # pretend that 50 is zero my_dat2$temp <- my_dat2$temp-50 ggplot(my_dat2, aes(x=x, y=temp, fill=temp)) + geom_bar(stat='identity') +...

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

r,plot,ggplot2

Try this, library(gtable) library(grid) library(ggplot2) exprGrob <- function(..., parse=TRUE, spacing=unit(0.5,"line")){ labs <- list(...) if(parse) labs <- lapply(labs, function(x)parse(text=x)) labs <- lapply(labs, textGrob, gp=gpar(fontface="bold",fontfamily="Times")) widths <- do.call(unit.c, lapply(labs, grobWidth)) heights <- do.call(unit.c, lapply(labs, grobHeight)) g <- gtable_matrix(name = "expr", grobs = matrix(labs, ncol=1, nrow=length(labs)), widths = max(widths), heights = heights+spacing) g...

showing different units in each free_y of facet_grid

r,ggplot2,facet-wrap

as a fragile workaround, you could use label_fun <- function (x) { if(max(x, na.rm=TRUE) > 1) dollar(x) else percent(x) } (assuming you only deal with big money and small percentages)...

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

r,ggplot2,traminer

All the information (sequences, alphabet, color palette, short and long state labels, position labels, ...) used by seqIplot is in the state sequence object you define with seqdef from your raw data. So just explore your object using attributes library(TraMineR) data(mvad) ## create a state sequence object from columns 17...

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

r,ggplot2

There's some good discussion here about why plotting with two different y-axes is a bad idea. I'll limit to plotting the sales and cumulative percentage separately and displaying them next to each other to give the full visual representation of the Pareto chart. # Sales df <- data.frame(country, sales) df...

combined use of geom_boxplot and scale_x_datetime

r,ggplot2

This seems to work as I expected. (You never did say how you expected.) plot2 = plot1 + scale_x_discrete(labels=format.Date(x, "%Y/%m/%d %H")) plot2 The point here is that you created an x-factor variable by using: aes(x=factor(a), y=b) so any label formatting needs to respect the mode of the x-variable. I don't...

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

r,plot,ggplot2,melt

There are two problems here. The first problem is that you use as.POSIXlt that produces lists instead of as.POSIXct which produces vectors. Therefore melt cannot do its job properly. Try this instead: df$time <- as.POSIXct(paste(df$Date, df$Time)) The second problem is that you group on the same variable that is used...

Plotting with ggplot through calling another function

r,ggplot2

Your example is not very clear because you give a call but you don't show the values of your variables so it's really hard to figure out what you're trying to do (for instance, is method the name of a column in the data frame pl1, or is it a...

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

r,plot,ggplot2

This should work gaps = data.frame(gap.pos = c(50646312, 50647076, 50647511, 50647512, 50647513, 50647546)) gap_plot <- ggplot(gaps) + geom_point(aes(x=gap.pos, y=1)) you have to call the plot you produced to actually see the plot gap_plot ...

Sequence index plots in ggplot2 using geom_tile( )

r,ggplot2,traminer

Two small changes: mvad_long$id <- as.factor(mvad_long$id) ggplot(data=mvad_long,aes(x=Month,y=id,fill=state))+ geom_tile()+facet_wrap(~cluster,scales = "free_y") ggplot was treating id as a numerical variable, rather than a factor, and then the scales were fixed....

Adjust space between gridded, same-sized ggplot2 figures

r,ggplot2,gridextra

You have set the 'widths' to be the maximums of the two plots. This means that the widths for the y-axis of the 'Petal Widths' plot will be the same as the widths of the y-axis of the 'Sepal Widths' plot. One way to adjust the spacing is, first, to...

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

r,function,ggplot2

You can use shQuote to quote the string and scale_fill_manual to map the strings to appropriate colors x_var <- "Score" ggplot(met1, aes_string(x_var)) + geom_density(data=met1, aes_string(x=x_var, fill=shQuote("b"))) + geom_density(data=met1[met1$Group=="Group1",], aes_string(x=x_var, fill=shQuote("r")), alpha=0.50) + scale_fill_manual(name='Groups', guide='legend', values=c("b"="black", "r"="red"), labels=c('All Groups', 'Group1')) ...

error with lapply on anonymous ggplot function

r,plot,ggplot2

You are missing a paranthesis to close ggtitle() as names() also requires a closing paren. 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",...

Log Scale Transformation in R for ggplot2

r,ggplot2

The book of Hadley is already quite old in regards to dynamics in programming. To my experience ggplot2 is quite a dynamic package and these details often change (also see questions referring to how to turn the labels on the axis). Due to that I prefer to check stuff like...

ggplot2 shapes by variables with replicates [duplicate]

r,ggplot2,shapes

Besides the fact that you have a typo in aes ( shape and not shapes) , you need to set a scale_shape_manual : ggplot(DX, aes(x = PRICE, y = SPEED, colour = COUNTRY, shape = BRAND))+ geom_point(size = 3)+ stat_summary(fun.data = "mean_cl_boot", colour = "green") + scale_shape_manual(values=c( 24, 22, 21,...

Issue with geom_text when using position_dodge

r,ggplot2

Just one minor change solves the issue. You need to specify group=x inside your geom_text(aes(...)) call. ggplot(df) + geom_bar(aes(z, y, fill=x), position=position_dodge(width=1), stat="identity") + geom_text(aes(z,y,label=perc, group=x), position=position_dodge(width=1), size=4) ...

Grouped barplot in ggplot2 in R

r,ggplot2,bar-chart

If you want separate bars for each gear, then you should add fill=gear to the aes in geom_bar: ggplot(cdata[cdata$year==2012 & cdata$sitecode==678490,], aes(x = factor(month), y = totalvalue, fill=gear)) + geom_bar(stat = "identity", position="dodge") + labs(x = "Month", y = "Total value") this gives: When you want to make a plot...

Dynamically create expression for ggplot legend?

r,ggplot2,expression,legend

ggplot(plot.df, aes(x, y, colour = grp)) + stat_smooth(method = "loess", se = F) + geom_line(aes(y = pred)) + scale_color_manual(values = setNames(geom.colors, paste0("x^",poly.degree)), labels = setNames(lapply(poly.degree, function(i) bquote(x^.(i))), paste0("x^",poly.degree))) It's important to ensure correct mapping if you change values or labels in the scale. Thus, you should always use named vectors....

ggplot format italic annotation

r,ggplot2

Use parse=TRUE and supply a string formatted according to ?plotmath. p <- ggplot(d, aes(i, value, linetype=variable)) + geom_hline(yintercept=700^2) + geom_line() + scale_linetype_manual(values=c(2,1)) + scale_x_continuous(breaks=(0:20)*365/7, labels=0:20) + scale_y_sqrt() + annotate('text', 8*365/7, 1e3, label="P(italic(i))==8~italic(i)", parse=TRUE, hjust=1, size=3) + annotate('text', 8*365/7, 2.5e5, label="A(italic(i))==1+4~italic(i)(italic(i)-1)", parse=TRUE, hjust=1, size=3) ...

ggplot2 and first data point in a line

r,ggplot2,facet

Another option is to adjust text using hjust argument as an aes. But first you should add it to the data as its own column that you will pass into the ggplot command : library(data.table) DX <- setDT(df[df$MEPSID==1,]) DX[,hjust:=ifelse(Time==min(Time),0.1,ifelse(Time==max(Time),0.8,0.4)),Year] #This creates a new variable called hjust p2<-ggplot(DX, aes(x = Time,...

Making multiple plots with mapply

r,ggplot2,mapply

I think the problem came from the fact that the function is looking for a variable inside df named "var1". I don't know ggplots enough to circumvent this problem but, with base R plot, you can do: baseplot <- function(var1, var2){ plot(df[,var1], df[,var2], pch=19) } par(mfrow=c(1, 2)) mapply(baseplot, c("V1", "V3"),...

Equal distance among all points on an axis

r,ggplot2,scatter-plot

You might want to convert your x-values into factors. Right now, R assumes that your x-values are numbers and hence puts the appropriate space between them (the difference between 5,884 and 13,957 is larger than the difference between 21,013 and 28,708). However, you probably think of the numbers as names...

Ploting the world map in R

r,ggplot2

You can also work in "layers" as other GIS environments let you (which will also let you not merge the data). This can be achieved in many ways, but I like to use geom_map: library(ggplot2) library(dplyr) WorldData <- map_data('world') WorldData %>% filter(region != "Antarctica") -> WorldData WorldData <- fortify(WorldData) df...

qplot - legend text in italics

r,ggplot2

Try sth like that p + theme(legend.text = element_text(face = "italic")) ...

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

r,ggplot2

This has to with with the lazy exaluation of parameters passed to qplot. The values aren't actually resolved till you print the plot. At that point, the value if i is just 6 after the looping. A better strategy would be plots <- lapply(1:6, function(i) { force(i) #required if you...

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

r,ggplot2,facet

The cause of the error: At the beginning of the function call, the elements of value all have class "character". But when you hit value[value=="secondary"] <- label_secondary a bunch of those elements get replaced by expressions. So when you then try to do value[value=="primary"] <- label_primary R is trying to...

Group values that occur only once into an OTHER field

r,ggplot2

Something like this: ## example data dd <- data.frame(DENOM=rep(LETTERS[1:7],c(10,5,4,rep(1,4)))) tt <- table(dd$DENOM) ## count occurrences singletons <- names(tt)[tt==1] ## find singletons tmpc <- as.character(dd$DENOM) ## convert from factor to char tmpc[tmpc %in% singletons] <- "OTHER" ## replace values dd$DENOM <- factor(tmpc) ## convert back to factor The only problem with...

replacing NAs by value but excluding from geom_smooth

r,ggplot2

One way to do it is to store your data into two different data frames : df2 <- df df2[is.na(df2)] <- -5 And plot them into two different layers : ggplot() + geom_point(data=df2, aes(x,y)) + geom_smooth(data=df, aes(x,y), method="lm", fullrange=TRUE) But maybe a cleaner way to do it would be to...

ggplot + facet: dropping factors with no data

r,ggplot2

This can be done with na.omit in the following way: ggplot(na.omit(z), aes(EVTYPE, value, fill = variable)) + geom_bar(stat = "identity", position = "dodge") + facet_wrap( ~ variable, scales = "free") + theme(axis.text.x = element_text(angle=90, vjust=1)) Here's the result: Hope this helps....

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

r,ggplot2,data.table,lubridate

It looks like the code for geom_boxplot does division to try to calculate box widths. As far as I can tell that branch seem unavoidable. A hack-y workaround would be to actually define division for date time values. `/.POSIXt`<-function(e1,e2) as.numeric(e1)/as.numeric(e2) Running this before your code seems to produce the requested...

Overlaying jittered points on boxplot conditioned by a factor using ggplot2

r,ggplot2,overlay,boxplot,jitter

Welcome to SO! Here's my attempt. It's a bit clumsy, but does the job. The trick is to map x to a dummy variable with manually constructed offset. I'm adding a fill scale to highlight point positioning. mtcars$cylpt <- as.numeric(factor(mtcars$cyl)) + ifelse(mtcars$am == 0, -0.2, 0.2) ggplot(mtcars, aes(factor(cyl), mpg)) +...

Fitting a polinomial curve to time series data

r,ggplot2,time-series,lm

try using mean instead of sum like this ggplot(data = df, aes(x = Month, y = Count.V)) + stat_summary(fun.y = mean, geom ="line")+ stat_smooth(method = "lm", formula = y ~ poly(x, 3), size = 1) + geom_point()+ scale_x_date(labels = date_format("%m-%y"), breaks = "3 months") ...

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

r,ggplot2,dplyr,tidyr

As mentioned by @Spacedman, you example is not reproducible/consistent. Part 1 This works: filter(mydata, measure == "pagesubmit") %>% ggplot(aes( y = as.numeric(value), x = as.factor(subject_instance), color = as.factor(subject_instance))) + geom_boxplot() Part 2 If you want the mean of all measure equal to pagesubmit, you can do: filter(mydata, measure == "pagesubmit")...

Plotting multivariate time-series data in R

r,graph,plot,ggplot2,time-series

Two ways of doing this: If sample data created as follows: Full.df <- data.frame(Date = as.Date("2006-01-01") + as.difftime(0:364, units = "days")) Full.df$Month <- as.Date(format(Full.df$Date, "%Y-%m-01")) Full.df[paste0("Count.", c("S", "G", "W", "F"))] <- matrix(sample(100, 365 * 4, replace = TRUE), ncol = 4) Optimal way using reshape2 package: molten <- melt(Full.df, id.vars...

ggplot equivalent for matplot

r,ggplot2

You can create a similar plot in ggplot, but you will need to do some reshaping of the data first. library(reshape2) #ggplot needs a dataframe data <- as.data.frame(data) #id variable for position in matrix data$id <- 1:nrow(data) #reshape to long format plot_data <- melt(data,id.var="id") #plot ggplot(plot_data, aes(x=id,y=value,group=variable,colour=variable)) + geom_point()+ geom_line(aes(lty=variable))...

How to add inbetween space in nested boxplots ggplot2

r,ggplot2,boxplot

I have fixed a similar problem in an ugly (but effective for me) way by creating a dataframe with the same plotting variables as my original data, but with x (or y) positioned or factored that it fits between the two points I want to separate and missing values for...

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

r,ggplot2

To sum up what was said in the comments : Your y-axis is indeed sorted but according to the character values (or rather the factor levels, as your variable was imported as factor) and not the numeric ones (so 1, 10, 11, ..., 2, 20, ...) There is 2 problems...

How to customize lines in ggpairs [GGally]

r,ggplot2,ggally

I hope there is an easier way to do this, but this is a sort of brute force approach. It does give you flexibility to easily customize the plots further however. The main point is using putPlot to put a ggplot2 plot into the figure. library(ggplot2) ## First create combinations...

Create abbreviated legends manually for long X labels in ggplot2

r,ggplot2,legend

Rotation solution suggested by Pascal Rotate the labels and align them to the edge : datas %>% ggplot(aes(x = label, y = freq)) + geom_bar(aes(fill = type), stat = "identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ...

stuck making a data frame after using street2coordinates (R)

r,google-maps,ggplot2

Currently, your do.call creates a matrix (using rbind and c), coercing all the numeric into characters. The following should turn your list "json" into the data.frame "geocode" will the information you need, i.e. "address", "long" and "lat". foo <- function(x) data.frame(address=paste(x$street_address, x$locality, x$region), long=x$longitude,lat=x$latitude) geocode <- do.call(rbind, sapply(json, foo)) ...

Cannot produce ggplot2 in Shiny

r,ggplot2,shiny,ecdf

You have a reactive data set in datasetInput but you aren't using it in your plotting function. In your ggplot call just replace mydf_m with datasetInput(). I also replaced renderGvis with renderPlot and return the data from the reactive datasetInput. The server is then server <- shinyServer(function(input, output) { datasetInput...

Adding partial horizontal lines with ggplot2 in R

r,ggplot2

Try geom_segment: ggplot(mydf, aes(a, b)) + geom_point()+ geom_vline(xintercept=50) + geom_segment(aes(x=a, xend=50, y=b, yend=b), colour="blue") ...

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

r,ggplot2

What is happening here is that ggplot is not stacking the error bars (they would have to be summed) so you will have to do that by hand (and it seems that Hadley thinks that this is not a good idea and wil not add this functionality). So doing by...

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

r,plot,ggplot2

For the coloured lines, just add a colour argument p = ggplot() + stat_summary( data = d0_400, ..., geom="line", colour = "#hexnum" ) Also, a quick google of the optional question took me to here: The solution provided is p = p + guides(shape=guide_legend(override.aes=list(size=5))) ...

Shiny + GGplot - mouse click coordinates

ggplot2,shiny,rstudio

I find a way to resolve: imagens and codes: https://github.com/faustobranco/StackQuestions library(shiny) library(ggplot2) ui <- fluidPage( plotOutput("plot", click = "plot_click"), verbatimTextOutput("info") ) server <- function(input, output, session) { output$plot <- renderPlot({ ggplot(cars, aes(speed, dist)) + geom_bar(stat="identity") }) output$info <- renderText({ xy_str <- function(e) { if(is.null(e)) return("NULL\n") paste0("x=", round(e$x, 1), "\n") }...

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

r,plot,ggplot2

OK I figure it out by myself ggplot(data, aes(x=V2, color=V1)) + geom_density(aes(group=V1)) Should be able to do that. However there is two thing I need to make sure first in order to let it run: V1 is a factor V2 is a numerical value The data I got wasn't set...

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

r,ggplot2,order,facet

you can use reorder and interaction between groups and Category like this ggplot(df,aes(x=reorder(interaction(Category, Group), -Amount, sum),y=Amount)) + geom_bar(stat='identity') + facet_wrap(~Group,scales='free_x') + labs(title="Some Random Histogram with Facets") ...

ggplot2 & facet_wrap - eliminate vertical distance between facets

r,ggplot2

Change the panel.margin argument to panel.margin = unit(c(-0.5,0-0.5,0), "lines"). For some reason the top and bottom margins need to be negative to line up perfectly. Here is the result: ...

How to plot a lagged time series?

r,ggplot2

You can use tail to get a lagged version a vector: tail(x,-1) But within ggplot2 aesthetics must either be length one or having the same length, so you should append a value to the lagged one in order to plot it against the original vector. For example: x= 1:10 qplot(x=x,y=c(tail(x,-1),0))...

geom_rect() main variable not found

r,ggplot2

OK. This: geom_rect(inherit.aes = FALSE, data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4) ...

How to execute .r files to output figures?

r,ggplot2

First, you need to ensure that the R software where you will run your scripts, has all required packages installed. Second, make sure the data is somehow available. This should usually make all scripts runnable. If you want to save ggplot-figures, use the ggsave-function after each plot is generated. This...

Setting limits with scale_x_datetime and time data

r,ggplot2,time-series

the error message says that you should use as.POSIXct on lims. You also need to add the date (year, month and day) in lims, because by default it will be `2015, which is off limits. lims <- as.POSIXct(strptime(c("2011-01-01 03:00","2011-01-01 16:00"), format = "%Y-%m-%d %H:%M")) ggplot(df, aes(x=dates, y=times)) + geom_point() +...

Assign Specific Colors to Specific Values [duplicate]

r,ggplot2

You need, as you say, to specify the order of your factor levels: x$value = factor(x$value, levels = c("ONE", "TWO", "THREE", "FOUR")) # the order of the vector you pass to levels defines the order of the factor Then you need to define your color vector in the same order....

Conditionally change ggplot facet background with date axis

r,ggplot2,facet

The cause of your error message was that you tried to map an aesthetic to a column that doesn't exist in your data, in this line: geom_rect(data = facetcond, aes(fill = "red"), You are not mapping an aesthetic, but telling ggplot to fill the rectangle with red. The line should...

Draw geom_smooth only for fits that are significant

r,ggplot2,statistics

You can calculate the p-values by group and then subset in geom_smooth (per the commenters): # Determine p-values of regression p.vals = sapply(unique(d$z), function(i) { coef(summary(lm(y ~ x, data=d[z==i, ])))[2,4] }) plt <- ggplot(d) + aes(x=x, y=y, color=z) + geom_point() # Select only values of z for which regression p-value...

Set categorical axis labels with scales “free” ggplot2

r,plot,ggplot2,facet

The easiest method would be to create another column in your data set with the right conversion. This would also be easier to audit and manipulate. If you insist on changing manually: You cannot simply set the labels directly, as it recycles (I think) the label vector for each facet....

Only show last four labels on bar graph

r,ggplot2

Thanks to @user20650 for the quick response. Subsetting the gem_text did the trick. Thank you very much! Here is the updated code: 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") + geom_text(data=subset(df, x>6), aes(y=y, ymax=y, label=y), position= position_dodge(width=0.9), vjust=-.5, color="red") ...

ggplot2 heatmap scaling row

r,ggplot2

How about rescaling before melting: dataRowNorm <- t(apply(data, 1, function(x) x/sum(x))) Then melt, rename columns possibly and pass to ggplot....

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

r,ggplot2

What if you change the linetype by group? p <- ggplot(dat = visual12, aes(x = as.numeric(weight), group = interaction(group, sexe), linetype=factor(group), col = sexe)) + stat_ecdf(geom = "step") + scale_colour_brewer(name = "sexe", palette = "Set1") + theme(axis.text = element_text(size = 15), legend.justification = c(1, 0), legend.position = c(1, 0), axis.text.x...

Overriding panel.grid in ggplot2

r,ggplot2

If you look at theme_grey you can see that panel.grid.minor and panel.grid.major are both specified. When you specify panel.grid to a specific color, the minor and major grid lines would inherit this if a color wasn't specified for them. But there is. This works as expected: p_grid <- qplot(data =...

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

r,plot,ggplot2,axis-labels

Building on @Stibu answer and comment, this solution takes into account number of groups and uses the intelligent splitting developed by Stibu, while adding a fix for words separated by a slash. Functions: #Inserts newlines into strings every N interval new_lines_adder = function(x, interval) { #add spaces after / x...

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

r,pdf,plot,ggplot2

I can reproduce the bug. The solution , add (push viewport) a viewport to the vieport tree to insert the grid plot. But it forget to remove it ( pop viewport). Adding the line at the ned will fix the problem : popViewport() Test the solution: To test this fix,...

R Biplot with clusters as colors

r,ggplot2,pca

I think you should try theme(legend.position="none"). library(factoextra) plot(fviz_pca_biplot(pca, label="var", habillage=as.factor(kc$cluster)) + ggtitle("") + theme(text = element_text(size = 15), panel.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"), legend.position="none")) This is what I get: ...

R ggplot2 boxplot not properly shown when knitting html

r,ggplot2,boxplot

The most likely difference is that you forgot to make quality into a factor within your rmd file. For example: set.seed(101) dd <- data.frame(quality = sample(6:9,size=200,replace=TRUE), residual.sugar = rnorm(200)) library(ggplot2) ggplot(aes(x = quality, y = residual.sugar),data=dd)+ geom_boxplot() dd2 <- transform(dd,quality=factor(quality)) ggplot(aes(x = quality, y = residual.sugar),data=dd2)+ geom_boxplot() ...

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

r,plot,ggplot2

You could do this, but it requires a bit of manual tuning of the scale to look decent. plot.df <- data.frame(band = rep(bands, count), count = unlist(lapply(count, seq_len))) ggplot(plot.df, aes(x = count, y=band)) + geom_point() + scale_x_continuous(limits=c(0, 10), breaks=seq(0, 10, by=2) ...

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

r,plot,ggplot2

Shamefully taken from Ari's post on gis.stackexchange.com. See the link for pictures. There are more examples here. library(sp) Srs1 = Polygons(list(Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))), "s1") Srs2 = Polygons(list(Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))), "s2") SpDF <- SpatialPolygonsDataFrame( SpatialPolygons(list(Srs1,Srs2)), data.frame(z=1:2, row.names=c("s1","s2") ) ) spplot(SpDF, zcol="z") ...

Scaling Time in Hours in ggplot2

r,ggplot2

I wonder if it's a timezone thing. Look at the output of attributes(dfweek2$Time) and see if it has a tzone attribute. If it does, then when format is called without a tz parameter, it will convert the times from whatever time zone they're stored as to whatever system time zone...

Limit the color variation in R using scale_color_grey

r,colors,ggplot2

I think this code should produce the plot you want. However, without your exact dataset, I had to generate simulated data. ## Generate dummy data and load library library(ggplot2) df4 = data.frame(Remain = rep(0:1, times = 4), Day = rep(1:4, each = 2), Genotype = rep(c("wtb", "whd"), each = 4),...

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

r,plot,ggplot2

You want a data frame with a row for each team-year combination, containing the data for that year and the next year as well as the team name. You can actually get this without any split-apply-combine manipulation using base R functions: (to.plot <- data.frame(yearN=unlist(df[-ncol(df)]), yearNp1=unlist(df[-1]), team=rep(row.names(df), ncol(df)-1))) # yearN yearNp1...

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

r,plot,ggplot2,rstudio,boxplot

ggplot2 requires that your data to be plotted on the y-axis are all in one column. Here is an example: set.seed(1) df <- data.frame( value = runif(810,0,6), group = 1:9 ) df library(ggplot2) ggplot(df, aes(factor(group), value)) + geom_boxplot() + coord_cartesian(ylim = c(0,6) The ylim(0,6) sets the y-axis to be between...

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

r,plot,ggplot2,cdf

Combining the example by @Robert and code from the answer featured here: How to get a reversed, log10 scale in ggplot2? library("scales") library(ggplot2) reverselog_trans <- function(base = exp(1)) { trans <- function(x) -log(x, base) inv <- function(x) base^(-x) trans_new(paste0("reverselog-", format(base)), trans, inv, log_breaks(base = base), domain = c(1e-100, Inf)) }...

Creating new shape palettes in ggplot2 and other R graphics

r,graphics,ggplot2

You can create your own shape palette by specifying the Unicode values for the characters you want. You can find Unicode values for various geometric shapes here. For example: library(ggplot2) ggplot(mtcars[mtcars$carb %in% 1:4,], aes(wt, mpg, shape=factor(carb), colour=factor(carb))) + geom_point(size=5) + scale_shape_manual(values=c("\u25BA","\u25C4","\u25BC","\u25B2")) You can, of course, use Unicode characters in base...

splitting or removing graphs after arrangeGrob

r,ggplot2,gridextra

First, use grid.ls() to see a listing of the grobs that make up the plot. Here, you'll be looking for the names of the two gTree objects that encode the individual plots. (Compared to lattice, ggplot2's naming of component grobs is relatively unhelpful, although in this case, it's not too...

How to modify ggplot2 scater plot

r,ggplot2

Yes, broadly speaking you are looking at creating a bubble plot, this code: df1 = data.frame(Count.amp = c(8,8,1,2,2,5,8), Count.amp.1 = c(4,4,2,3,2,5,4)) df1$sum <- df1$Count.amp + df1$Count.amp.1 ggplot(df1, aes(x=Count.amp, y=Count.amp.1, size=sum),guide=FALSE)+ geom_point(colour="white", fill="red", shape=21)+ scale_size_area(max_size = 15)+ theme_bw() would give you something like that: It wasn't immediately clear to me what...

geom_bar define border color with different fill colors

r,ggplot2

You have to put colour outside aes: ggplot(test) + geom_bar(aes(x=a, y=b, fill=c), colour="black", stat="identity") ...

Dodge points in point char with ggplot2

r,ggplot2

A roundabout solution: you can do horizontal dodge and flip the axes p = ggplot(data=df, aes(x=count, y=year, group=type, color=type)) + geom_line(position=position_dodge(width=1)) + geom_point(position=position_dodge(width=1)) + coord_flip() p ...

Align text right justified but center of each box in geom_text

r,ggplot2,geom-text

Use hjust=0.5 in geom_text() and pad the labels for positive numbers appropriately, i.e. prepend space characters to obtain labels of equal length: df_graph$text <- format(round(df_graph$value, 2)) ...

Subgroup Boxplots in R

r,ggplot2,visualization

Is this close to what you had in mind? There's a boxplot for each value of peer for each year. I've also included the mean values for each group. # Boxplots for each combination of year and peer, with means superimposed ggplot(dat, aes(year, pct, group=interaction(year,peer), colour=factor(peer))) + geom_boxplot(position=position_dodge(width=0.4), width=0.4) +...

R: ggplot2: plot initiating at the axes

r,ggplot2

The answer first, then an explanation. Add the line: coord_cartesian(xlim=c(0,max(sfit$time))) to your ggplot object. A simple example: df <- data.frame(c(runif(10,0,1)),runif(10,0,1)) names(df) <- c("x","y") p <- ggplot(df, aes(x,y)) + geom_point() + scale_x_continuous(breaks=c(0,0.25,0.5,0.75,1.0), labels=c("0","0.25","0.5","0.75","1.0")) p gives you whereas, if you add to the above code p <- p + coord_cartesian(xlim=c(0,1)) p you...

Plotting in R 3.1.2 [closed]

r,plot,ggplot2,ggmap

Perhaps something like this is what you're after, but this would be easier if you would provide sample data and be more descriptive in the exact question you are asking: library(ggplot2) library(dplyr) library(tidyr) df <- data.frame(id = 1:400, state = state.abb, ind1 = rnorm(400), ind2 = rnorm(400), ind3 = rnorm(400))...

skip the empty dataframes and produce the output

r,merge,ggplot2,tidyr,rpostgresql

Judging from the error message, the data.frame that causes the error has neither rows nor columns, it seems to be NULL. So the easiest way would be to check for that situation and if the data.frame is NULL, create a a dummy that can be merge()d and gather()ed. What I...