繁体   English   中英

ggplot2(Barplot + LinePlot) - 双Y轴

[英]ggplot2 (Barplot + LinePlot) - Dual Y axis

我很难用ggplot2重新创建一个excel示例。 我尝试了很多例子但由于某些原因我无法达到我想要的结果。 有人可以看看我的例子吗?

df <- structure(list(OccuranceCT = c(4825, 9063, 10635, 8733, 5594, 
2850, 1182, 376, 135, 30, 11), TimesReshop = structure(1:11, .Label = c("1x", 
"2x", "3x", "4x", "5x", "6x", "7x", "8x", "9x", "10x", "11x"), class = "factor"), 
    AverageRepair_HrsPerCar = c(7.48951898445596, 6.50803925852367, 
    5.92154446638458, 5.5703551356922, 5.38877037897748, 5.03508435087719, 
    4.92951776649746, 4.83878377659575, 4.67829259259259, 4.14746333333333, 
    3.54090909090909)), .Names = c("OccuranceCT", "TimesReshop", 
"AverageRepair_HrsPerCar"), row.names = c(NA, 11L), class = "data.frame")

我的情节到目前为止:

Plot <- ggplot(df, aes(x=TimesReshop, y=OccuranceCT)) +
  geom_bar(stat = "identity", color="red", fill="#C00000") +
  labs(x = "Car Count", y = "Average Repair Per Hour") + 
  geom_text(aes(label=OccuranceCT), fontface="bold", vjust=1.4, color="black", size=4) +
  theme_minimal()

Plot

这是我到目前为止所得到的:

1

而我想要实现的目标是:

2

我将很高兴学习如何添加辅助轴并将条形图与线图结合起来。

这个答案是对你的评论的回复,而不是原来的问题。

从宽到长重塑意味着我们有一列用于因变量(OccuranceCT,AverageRepair_HrsPerCar),另一列用于它们的值。 然后我们可以将它们作为条形图,在它们自己的方面,如下:

library(tidyr)
library(ggplot2)

df %>% 
  gather(variable, value, -TimesReshop) %>% 
  ggplot(aes(TimesReshop, value)) + 
    geom_col() + 
    facet_grid(variable ~ ., scales = "free")

这允许对变量进行快速视觉比较,而没有可能产生误导性的解释,这些解释可能是由于在同一图中将不同的变量放在不同的值上而产生的。

在此输入图像描述

ggplot2支持双轴(好或坏),其中第二轴是主轴的线性变换。

我们可以为这个案例解决这个问题:

library(ggplot2)
ggplot(df, aes(x = TimesReshop)) +
  geom_col(aes( y = OccuranceCT, fill="redfill")) +
  geom_text(aes(y = OccuranceCT, label = OccuranceCT), fontface = "bold", vjust = 1.4, color = "black", size = 4) +
  geom_line(aes(y = AverageRepair_HrsPerCar * 1500, group = 1, color = 'blackline')) +
  geom_text(aes(y = AverageRepair_HrsPerCar * 1500, label = round(AverageRepair_HrsPerCar, 2)), vjust = 1.4, color = "black", size = 3) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / 1500)) +
  scale_fill_manual('', labels = 'Occurance', values = "#C00000") +
  scale_color_manual('', labels = 'Time Reshop', values = 'black') +
  theme_minimal()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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