绘制条形和直线以及两个y轴

问题描述 投票:0回答:1

我需要绘制一个显示计数的条形图和一个显示平均值的折线图。这一切都在一个图表中,有多个y轴。

以下是数据帧的示例:

df <- data.frame("YearMonth" = c(20141, 20142, 20143, 20144), "Count" = c(435, 355, 360, 318), "Average" = c(107, 85, 86, 74))

如何才能做到这一点?

非常感谢。

r ggplot2 axes
1个回答
1
投票

{ggplot2} intentionally does not support this kind of multiple y-axes因为广泛的共识认为它们是一个坏主意,因为它们会引起对数据的错误解释。参见例如Why not to use two axes, and what to use instead

我们认为,具有两个不同y轴的图表使得大多数人难以直观地对两个数据系列做出正确的陈述。我们强烈推荐两种选择:使用两个图表而不是一个图表并使用索引图表。

{ggplot2}支持的唯一一种辅助y轴是主轴的缩放,请参阅sec_axis。这样的辅助轴不会遇到同样的问题,但它在您的场景中不起作用:您想要的确实是{ggplot2}故意不支持的情况之一。

但是,您可以做的是复制单个y轴,并覆盖条形和平均值(尽管在这种情况下不清楚条形代表什么):

# fix the `YearMonth` column:
df$YearMonth = lubridate::ymd(paste(sub('(.)$', '0\\1', as.character(df$YearMonth)),'01'))

ggplot(df) +
    aes(YearMonth) +
    geom_col(aes(y = Count)) +
    geom_line(aes(y = Average), size = 2, color = 'lightblue') +
    scale_y_continuous(sec.axis = dup_axis(name = NULL))

dual y-axis

© www.soinside.com 2019 - 2024. All rights reserved.