Reputation: 1651
I am plotting multiple bar graphs to compare the values in data of this type this is the contents of df4 where combinations of time_step and disturbance_type will be unique. I am doing this for data qaqc, and this is a small sample of the data I have.
time_step disturbance_type_id variable value
1 1 difference 8.040223e+01
10 1 difference 5.520571e+01
11 1 difference 2.145634e+02
12 1 difference 7.351697e+01
13 1 difference 6.682899e+00
14 1 difference 4.242542e+01
15 1 difference 2.102968e+01
16 1 difference 3.772944e+01
17 1 difference 6.365049e+01
1 2 difference 6.365049e+01
The code i am using to plot it is
differencePlot <- function(distTypeID)
{
p<-ggplot(data=df4[df4[2]==distTypeID,], aes(x=time_step, y=value, fill=value)) +
geom_bar(position="dodge",stat="identity") +
ylab("percent difference in disturbance area") +
ggtitle(paste("disturbance type ", distTypeID))
ggsave(filename=paste("disturbancesByTimeStepAndProject\\", "disturbance_area_differences_", distTypeID, ".png", sep=""), plot=p )
}
lapply(unique(df4$disturbance_type_id), function(x) differencePlot(x))
So I am essentially creating 1 bar graph file for each disturbance unique type id. When the function is called, and multiple rows of timesteps exist within the given disturbance_type_id all is well, but when the function is called with distTypeID = 2 (where only a single row of data will exist), the function fails with this error message.
Error in grid.Call.graphics(L_raster, x$raster, x$x, x$y, x$width, x$height, :
Empty raster
Is it not possible to graph with a single bar? Any ideas?
Upvotes: 2
Views: 2964
Reputation: 93761
This appears to be a known bug in ggplot2. You can work around it by creating an if ... else statement in your function that checks for a single row of data. In that case you'll want your code to set the bar color outside of aes
. For example:
p <- ggplot(data=df4[df4[2]==distTypeID,], aes(x=time_step, y=value)) +
geom_bar(position="dodge",stat="identity", fill="blue") +
ylab("percent difference in disturbance area") +
ggtitle(paste("disturbance type ", distTypeID))
Upvotes: 1