简体   繁体   中英

R: plotting a line and horizontal barplot on the same plot

I am trying to combine a line plot and horizontal barplot on the same plot. The difficult part is that the barplot is actually counts of the y values of the line plot.

Can someone show me how this can be done using the example below ?

library(ggplot2)
library(plyr)
x <- c(1:100)
dff <- data.frame(x = x,y1 = sample(-500:500,size=length(x),replace=T), y2 = sample(3:20,size=length(x),replace=T))

counts <- ddply(dff, ~ y1, summarize, y2 = sum(y2))

# line plot
ggplot(data=dff) + geom_line(aes(x=x,y=y1)) 
# bar plot
ggplot() + geom_bar(data=counts,aes(x=y1,y=y2),stat="identity")  

I believe what I need is presented in the pseudocode below but I do not know how to write it out in R.

Apologies. I actually meant the secondary x axis representing the value of counts for the barplot, while primary y-axis is the y1 .

ggplot(data=dff) + geom_line(aes(x=x,y=y1)) + geom_bar(data=counts , aes(primary y axis = y1,secondary x axis =y2),stat="identity")  

在此处输入图片说明

I just want the barplots to be plotted horizontally, so I tried the code below which flip both the line chart and barplot, which is also not I wanted.

ggplot(data=dff) + 
  geom_line(aes(x=x,y=y1)) + 
  geom_bar(data=counts,aes(x=y2,y=y1),stat="identity") + coord_flip()

在此处输入图片说明

You can combine two plots in ggplot like you want by specifying different data = arguments in each geom_ layer (and none in the original ggplot() call).

 ggplot() + 
    geom_line(data=dff, aes(x=x,y=y1)) + 
    geom_bar(data=counts,aes(x=y1,y=y2),stat="identity") 

The following plot is the result. However, since x and y1 have different ranges, are you sure this is what you want?

在此处输入图片说明

Perhaps you want y1 on the vertical axis for both plots. Something like this works:

ggplot() + geom_line(data=dff, aes(x=y1 ,y = x)) +
geom_bar(data=counts,aes(x=y1,y=y2),stat="identity", color = "red") + coord_flip()

在此处输入图片说明

Maybe you are looking for this. Ans based on your last code you look for a double axis. So using dplyr you can store the counts in the same dataframe and then plot all variables. Here the code:

library(ggplot2)
library(dplyr)
#Data
x <- c(1:100)
dff <- data.frame(x = x,y1 = sample(-500:500,size=length(x),replace=T), y2 = sample(3:20,size=length(x),replace=T))
#Code
dff %>% group_by(y1) %>% mutate(Counts=sum(y2)) -> dff2
#Scale factor
sf <- max(dff2$y1)/max(dff2$Counts)
# Plot
ggplot(data=dff2)+
  geom_line(aes(x=x,y=y1),color='blue',size=1)+
  geom_bar(stat='identity',aes(x=x,y=Counts*sf),fill='tomato',color='black')+
  scale_y_continuous(name="y1", sec.axis = sec_axis(~./sf, name="Counts"))

Output:

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM