I am trying to run this following code:
p <- ggplot(data=cuernavaca.map, aes(long, lat, group=group))
p + geom_polygon(size=0.1, aes(fill=pobtot)) + coord_equal() + facet_wrap(~nombre_municipio,scales="free") + coord_equal() + scale_fill_gradient2(low="blue", high="red", midpoint=mean(cuernavaca.map$pobtot, na.rm=TRUE))+ tema.mapas + ggtitle("Cuervaca y Zona metropolitana\nPoblación Total") + labs(fill="Población total")
but I got this error:
Error: ggplot2 doesn't know how to deal with data of class uneval
The object cuernavaca.map is a fortified SpatialDataFrame.
The weird thing is that this only happens in one machine (Ubuntu 13.04, RStudio 0.97.551, R 3.0.1) when I execute the knit2html or I hit the button knit HTML, If I execute the lines of code in the console (inside RStudio) everything works (I mean, the plot is done), If I cut and paste that code in other .Rmd file it works and If I execute it in another Ubuntu box (same specs as above) or MacOS X, it works!
Any ideas?
UPDATE:
As is written in the comments, the problem seems to be the order of the unnamed parameters, so I change the code to this:
ggplot(data = cuernavaca.map) +
geom_polygon(mapping = aes(x = long, y = lat, group = group, colour = NA, fill = pobtot)) +
coord_equal() +
facet_wrap(~nombre_municipio, scales = "free") +
scale_fill_gradient2(low = "blue", high = "red", midpoint = mean(cuernavaca.map$pobtot,
na.rm = TRUE)) +
tema.mapas +
ggtitle("Cuervaca y Zona metropolitana\nPoblación Total") +
labs(fill = "Población total")
And know is everything working ... almost.
If you see the code I remove the size parameter in the geom_polygon and I set the colour to NA, I made that, not for aesthetics reasons, but because, that parameters are not working: the line width of the polygon gets enormous and the color is just ignored, sometimes gets light red, in others it just disappears...
As a funny thing, the plots below this one, are working now, too, but guess what? The code is the following:
ggplot(legend = FALSE) +
geom_polygon(data = cuernavaca.map, size = 0.1, aes(long,
lat, group = group, colour = "grey80", fill = ind_vul)) +
scale_fill_gradient2(low = "blue", high = "red", midpoint = mean(cuernavaca.map$ind_vul, na.rm = TRUE)) +
geom_point(data = puntos.df, aes(as.numeric(long), as.numeric(lat), colour = geografico), size = 2) +
facet_wrap(~municipio, scales = "free") +
tema.mapas +
labs(fill = "Índice de vulnerabilidad")
puntos.df is a data.frame with latitude and longitude, so no big deal, but not how the size parameters is out of the aes and is working (I am not getting a error of "not know how to deal with a numeric... blah blah")
Could be a memory issue?
As is told in the edit, the answer was using named parameters:
ggplot(data = cuernavaca.map) +
geom_polygon(mapping = aes(x = long, y = lat, group = group, colour = NA, fill = pobtot)) +
coord_equal() +
facet_wrap(~nombre_municipio, scales = "free") +
scale_fill_gradient2(low = "blue", high = "red", midpoint = mean(cuernavaca.map$pobtot, na.rm = TRUE)) +
There are some unanswered questions, but I posted a new one in: ggplot map with points: size, colour, legend, aesthetics problems
Related
I would like to change the dots in the next plot to the flag for the respective country. For this I know that geom_flag() could works, but... not for me but I got stuck with this error message:
Error in grobify(picture, x = x, y = y, width = width, height = height, :
object '.flaglist' not found
This is my code:
ggplot(df, aes(lenght, Ponto.Caspian)) +
geom_point()+ ggflags::geom_flag(aes(x = longitude, y = latitude+0.5, country = country))
maybe also geom_image() could work but I don't know how to link the flag with the country column...or How to use an image as a point in ggplot?, but I don't understand the process
This my desire plot, but changing dots to flags:
ggplot(df, aes(lenght, Ponto.Caspian)) +
geom_point(aes(colour = factor(country)))+
scale_fill_brewer(palette = "Set3")+ scale_x_continuous(breaks = seq(10, 40, by = 5))+
scale_y_continuous(breaks = seq(0, 16, by = 1))+
theme_classic2() + theme_cleveland()+ geom_smooth(method = "lm", alpha=0.2)+
stat_cor(label.x = 2, label.y = 1)
This is my data:
https://drive.google.com/drive/folders/1qR2mUdrpStOYBmxajc_F4nxS_qf-4bzf?usp=sharing
thanks in advance
It seems to work for me if I convert your countries to two-character ISO codes (which is what the example at https://github.com/jimjam-slam/ggflags uses).
I also had to load the ggflags library, rather than using ggflags::geom_flag
For example, using the countrycode package:
df$iso_code <- tolower(countrycode(df$country, origin = 'country.name', destination = 'iso2c'))
ggplot(df, aes(lenght, Ponto.Caspian)) +
geom_point() +
geom_flag(aes(x = longitude, y = latitude+0.5, country = iso_code))
I would like to change the y axis label (or main title would also be fine) of a ggplot to reflect the column name being iterated over within an apply function.
Here is some sample data and my working apply function:
trial_df <- data.frame("Patient" = c(1,1,2,2,3,3,4,4),
"Outcome" = c("NED", "NED", "NED", "NED", "Relapse","Relapse","Relapse","Relapse"),
"Time_Point" = c("Baseline", "Week3", "Baseline", "Week3","Baseline", "Week3","Baseline", "Week3"),
"CD4_Param" = c(50.8,53.1,20.3,18.1,30.8,24.5,35.2,31.0),
"CD8_Param" = c(5.3,9.7,4.4,4.3,3.1,3.2,5.6,5.3),
"CD3_Param" = c(11.6,16.6,5.0,5.1,14.3,7.1,5.9,8.1))
apply(trial_df[,4:length(trial_df)], 2, function(i) ggplot(data = trial_df, aes_string(x = "Time_Point", y = i )) +
facet_wrap(~Outcome) +
geom_boxplot(alpha = 0.1) +
geom_point(aes(color = `Outcome`, fill = `Outcome`)) +
geom_path(aes(group = `Patient`, color = `Outcome`)) +
theme_minimal() +
ggpubr::stat_compare_means( method = "wilcox.test") +
scale_fill_manual(values=c("blue", "red")) +
scale_color_manual(values=c("blue", "red")))
Example plot output
This creates 3 graphs as expected, however the y axis just says "y". I would like this to display the column name for the column in that iteration. It would also be fine to add a main title with this information, as I just need to know which graph corresponds to which column.
Here are things I have already tried adding to the ggplot code above based on some similar questions I found, but all of them give me the error "non-numeric argument to binary operator":
ggtitle(paste(i))
labs(y = i)
labs(y = as.character(i))
Any help or resources I may have missed would be greatly appreciated, thanks!
So.....for the strangest of reasons I cannot figure out why. This gives what you want but for only one graph!!!
apply(trial_df[,4:length(trial_df)], 2, function(i) ggplot(data = trial_df, aes_string(x = "Time_Point", y = i )) +
facet_wrap(~Outcome) +
geom_boxplot(alpha = 0.1) +
geom_point(aes(color = `Outcome`, fill = `Outcome`)) +
geom_path(aes(group = `Patient`, color = `Outcome`)) +
theme_minimal() +
stat_compare_means( method = "wilcox.test") +
scale_fill_manual(values=c("blue", "red")) +
scale_color_manual(values=c("blue", "red"))+
labs(y=colnames(trial_df)[i]))
Gives these:
I would create graph like this enter image description here
but I encountered problem : Error: Insufficient values in manual scale. 2 needed but only 1 provided
Here is my code
Library(ggplot2)
Library(read_xl)
df2 <- read_excel("Data122.xlsx", sheet = "sheet4")
ggplot(Data=df2) +
geom_line(aes(col="COP",
x =df2$`Ground Temp T1 Tg`,
y=df2$`Daily COP`), size= 2) +
theme_bw() +
labs(x = "Entering source temperature EST", y = "COP") +
geom_point() + theme(legend.position = "top") +
scale_color_manual(values=c("#FF3333")) +
theme(legend.title = element_blank()) +
scale_y_continuous(name = "COP",
sec.axis = sec_axis(trans = ~ . *1,
name = "Produced and Consumed power MWh")) +
geom_line(aes(col = "Consumed Power",
x = df2$`Ground Temp T1 Tg`,
y = df2$`Electricity MWh day`), size= 2)
**Insufficient values in manual scale. 2 needed but only 1 provided**
I would need as sample of your data to be sure, but your issues is in scale_color_manual(). You supplied a single color value to map to the data, but there must be two values in the data to map. If you want everything to be that color, don't map color as an aesthetic, just provide it as a parameter:
geom_line(aes(x =df2$`Ground Temp T1 Tg`,
y=df2$`Daily COP`), size = 2, color = "#FF3333")
Here are some other pointers about your code. In your aes() mappings, you have df2$. You don't need that. The whole reason of providing data = in the original ggplot() call is to avoid this.
geom_line(aes(x = `Ground Temp T1 Tg`,
y = `Daily COP`), size = 2, color = "#FF3333")
Your geom_point() layer has no aesthetics mapped, nor are there any defined in the ggplot() call. Layers do not inherit aesthetics from other layers. Your plot will not have any points on it.
Below is the a small dataset which i have tried to reproduce it to my best understanding.As in the attached plot you can observe that i am able to gradient in geom_point() but the same visuals i am trying for geom_line.Note : we are always been provided with data ofTempandvar.Thecat` variable is not given in data set.
df=data.frame(seq=(1:30),Temp =rnorm(30,mean = 34 ,sd=18))
f=summary(df$Temp)
df$cat <- cut(df$Temp,
breaks=c(f[1], f[3] ,f[4] ,f[6]),
labels=c("low","medium","high"))
f=ggplot(df , aes(x=seq ,y= Temp,colour=cat))+ geom_line()
f
Output of Above Code
Required Output
Gradient should as per High , Medium & Low using geom_line() function in ggplot2.
You want to group the lines by cat, but colour them by Temp. For getting a nice gradient, I like the colour scales in the viridis package, but you can play around with scale_colour_gradient instead:
library(viridis)
ggplot(df , aes(x=seq ,y= Temp,colour=Temp, group = cat)) +
geom_line(size = 1.2) +
scale_colour_viridis(option = "A")
Output:
To have a legend for the lines, you can represent cat with something like
shape:
ggplot(df , aes(x=seq ,y= Temp,colour=Temp, group = cat, shape = cat)) +
geom_point(size = 3) +
geom_line(size = 1.2) +
scale_colour_viridis(option = "A")
Is this what you want:
a <- data.frame(seq=(1:30),Temp =rnorm(30,mean = 34 ,sd=18))
ggplot(a, aes(x = seq, y = Temp, color = Temp )) +
geom_line(size = 0.5) +
geom_smooth(aes(color=..y..), size=1.5, method = "loess", se=FALSE) +
scale_colour_gradient2(low = "green", mid = "yellow" , high = "red",
midpoint=median(a$Temp))
While creating a shot chart in R, I've been using some open source stuff from Todd W. Schneider's BallR court design (https://github.com/toddwschneider/ballr/blob/master/plot_court.R)
along with another Stack Overflow post on how to create percentages within hexbins (How to replicate a scatterplot with a hexbin plot in R?).
Both sources have been really helpful for me.
When I run the following lines of code, I get a solid hexbin plot of percent made for shots for the different locations on the court:
ggplot(shots_df, aes(x = location_y-25, y = location_x, z = made_flag)) +
stat_summary_hex(fun = mean, alpha = 0.8, bins = 30) +
scale_fill_gradientn(colors = my_colors(7), labels = percent_format(),
name = "Percent Made")
However, when I include the BallR court design code snippet, which is shown below:
ggplot(shots_df, aes(x=location_y-25,y=location_x,z=made_flag)) +
stat_summary_hex(fun = mean, alpha = 0.8, bins = 30) +
scale_fill_gradientn(colors = my_colors(7), labels=percent_format(),
name="Percent Made") +
geom_path(data = court_points,
aes(x = x, y = y, group = desc, linetype = dash),
color = "#000004") +
scale_linetype_manual(values = c("solid", "longdash"), guide = FALSE) +
coord_fixed(ylim = c(0, 35), xlim = c(-25, 25)) +
theme_court(base_size = 22)
I get the error: Error in eval(expr, envir, enclos) : object 'made_flag' not found, even though that the made_flag is 100% in the data frame, shots_df, and worked in the original iteration. I am lost on how to fix this problem.
I believe your problem lies in the geom_path() layer. Try this tweek:
geom_path(data = court_points, aes(x = x, y = y, z = NULL, group = desc, linetype = dash))
Because you set the z aesthetic at the top, it is still inheriting in geom_path() even though you are on a different data source. You have to manually overwrite this with z = NULL.