用ggplot2 试试这个tidyverse 方法。双轴图的关键是在要显示在图中的变量之间有一个比例因子。代码如下:
library(tidyverse)
#Scaling factor
sf <- max(df$V2)/max(df$V3)
#Transform
DF_long <- df %>%
mutate(V3 = V3*sf) %>%
pivot_longer(names_to = "y_new", values_to = "val", V2:V3)
#Plot
ggplot(DF_long, aes(x=V1)) +
geom_bar( aes(y = val, fill = y_new, group = y_new),
stat="identity", position=position_dodge(),
color="black", alpha=.6) +
scale_fill_manual(values = c("blue", "red")) +
scale_y_continuous(name = "V2",labels = scales::comma,sec.axis = sec_axis(~./sf, name="V3",
labels = scales::comma))+
labs(fill='variable')+
theme_bw()+
theme(legend.position = 'top',
plot.title = element_text(color='black',face='bold',hjust=0.5),
axis.text = element_text(color='black',face='bold'),
axis.title = element_text(color='black',face='bold'),
legend.text = element_text(color='black',face='bold'),
legend.title = element_text(color='black',face='bold'))+
ggtitle('My barplot')
输出:
使用的一些数据:
#Data
df <- structure(list(V1 = c("abc", "xyz", "def"), V2 = c(862054L, 760369L,
488089L), V3 = c(111552197L, 163135388L, 130846735L)), class = "data.frame", row.names = c(NA,
-3L))