【问题标题】:How to fix/"lock" the y-axis-scale in ggplot2?如何修复/“锁定”ggplot2中的y轴比例?
【发布时间】:2018-04-25 23:25:01
【问题描述】:

我想比较 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,而不管实际数据集的最大值如何。

谢谢你! :)

【问题讨论】:

  • 如果可能的话,我还建议使用构面来绘制它,因为它默认固定轴

标签: r ggplot2 scale axis yaxis


【解决方案1】:

看起来你的 scale_y_continuous 覆盖了你之前设置的 ylim() 行,试试这个:

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

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多