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...
How about: ggplot(aes(x='date', y='entries_sum'), data=data) + geom_bar(stat='identity') ...
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...
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)) } ...
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,...
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...
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....
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)...
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() ...
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"),...
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...
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...
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...
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') +...
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...
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)...
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...
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...
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...
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...
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...
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 ...
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....
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...
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')) ...
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",...
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...
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,...
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) ...
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...
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....
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) ...
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,...
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"),...
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...
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...
Try sth like that p + theme(legend.text = element_text(face = "italic")) ...
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...
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...
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...
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...
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....
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...
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)) +...
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") ...
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")...
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...
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))...
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...
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...
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...
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)) ...
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)) ...
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...
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") ...
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...
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))) ...
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") }...
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...
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") ...
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: ...
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))...
OK. This: geom_rect(inherit.aes = FALSE, data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4) ...
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...
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() +...
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....
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...
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...
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....
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") ...
How about rescaling before melting: dataRowNorm <- t(apply(data, 1, function(x) x/sum(x))) Then melt, rename columns possibly and pass to ggplot....
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...
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 =...
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...
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,...
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: ...
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() ...
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) ...
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") ...
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...
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),...
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...
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...
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)) }...
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...
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...
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...
You have to put colour outside aes: ggplot(test) + geom_bar(aes(x=a, y=b, fill=c), colour="black", stat="identity") ...
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 ...
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)) ...
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) +...
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...
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))...
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...