I have the following plot and code. I wish to plot the "Plan" data
Here's a simple version of the data I'm using:
times=c("12AM", "1AM", "2AM")
times = factor(times, levels=c("12AM", "1AM", "2AM"),ordered = TRUE)
graph_df=data.frame(times,
c(12,15,18),
c(12,16,14),
c(12,17,20))
colnames(graph_df)=c("Time","LY", "TY", "Plan")
Here's the code I'm using for my ggplot:
library(ggplot2)
library(scales)
df_long=melt(graph_df)
ggplot(df_long,aes(Time,value,fill=variable))+
geom_bar(stat="identity",position="dodge")+
theme(text = element_text(size=10),axis.title.y=element_blank(),legend.title=element_blank(),
axis.title.x=element_blank(),plot.title = element_text(size=20),
axis.text.x = element_text(angle=45, vjust=1,colour = "black"),
axis.text.y = element_text(colour = "black"))+
#scale_y_continuous(expand = c(0,0), limits = c(0,1.1*max(graph_df[,2:4])),labels = dollar)+
ggtitle("Total Revenue to Plan")
You can run the provided code and see the graph it makes.
Here's my question: How do I make the Plan variable a line over the double bar graph I already have? I added the following to my ggplot
geom_line(aes(x=as.numeric(Time),y=graph_df$Plan))+
but got the error:
Error: Aesthetics must either be length one, or the same length as the dataProblems:graph_df$Plan
Any help would be greatly appreciated!
If you call your original graph g
, then use:
g + geom_line(data = graph_df,
mapping = aes(x = Time, y = Plan, group = 1),
inherit.aes = F)
Ggplot works best with data in data frames, so since you already have graph_df
keep it there! Also, you have a factor x axis established, so trying to convert your Time
to numeric is contradictory.
Typically, when adding a line for multiple categorical values, you need a grouping aesthetic so it knows which points to connect. Since you are only drawing one line, we can just set group to a constant.
Finally, since fill = variable
is in your initial plot, that aesthetic will be inherited by your line layer - which is a problem. I solve this by setting inherit.aes = F
for the line layer, but as Frank suggests you could also move the fill
mapping into the bar layer instead of the initialization... though y = value
might still throw things off (I didn't test).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.