如何修复/“锁定”ggplot2中的y轴刻度?

时间:2018-04-25 23:25:02

标签: r ggplot2 scale axis yaxis

我想比较5个图(条形图与温度线图重叠的频率),因为y比例必须在所有图中保持不变。但是当我绘制图形时,y尺度根据每个数据集的最大y值(=最大频率)进行调整。 这是我的代码:

ggplot(df) + 
    geom_bar(aes(hours,count), stat = "identity", fill = "gray92", colour = 
"gray92") +
    geom_line(aes(hours, percipitation*14), stat = "identity", size = 1.2) +
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.background = element_blank(),
          axis.line = element_line(colour = "black")) +
    ylab("Frequency") +
    ylim(0,80) +
    scale_y_continuous(sec.axis = sec_axis(~./14, name = "Percipitation [mm]"), breaks = seq(0,80,10)) +
    scale_x_continuous(breaks = c(0:23)) +
    theme(plot.title = element_text(size = 42, face = "bold", hjust = 0.5, margin = margin(0,0,35,0), 
          axis.title.x = element_text(size = 32, margin = margin(20,0,0,0),
          axis.title.y = element_text(size = 32, margin = margin(0,15,0,0)
          axis.title.y.right = element_text(size = 32, margin = margin(0,0,0,15), 
          axis.text.x = element_text(size = 18, margin = margin(7,0,0,0),
          axis.text.y = element_text(size = 18, margin = margin(0,5,0,0)),
          axis.text.y.right = element_text(size = 18, margin = margin(0,0,0,5)))

我希望所有图形都具有y比例:从0到80,无论实际数据集的最大值如何。

谢谢你! :)

1 个答案:

答案 0 :(得分:2)

看起来你的scale_y_continuous正在覆盖之前设置该行的ylim(),请尝试这样做:

scale_y_continuous(sec.axis = sec_axis(~./14, name = "Precipitation [mm]"), 
breaks = seq(0,80,10),limits = c(0,80))