如何在不重新缩放数据的情况下绘制带有并排条形图的 2-y 轴图表

amb*_*aka -1 r ggplot2

我的数据如下:

structure(list(Year = 1994:2016, Kcalpd = c(86L, 91L, 98L, 107L, 
116L, 126L, 123L, 112L, 103L, 102L, 103L, 92L, 77L, 59L, 43L, 
29L, 19L, 14L, 13L, 12L, 12L, 10L, 9L), Thtonnes = c(728.364, 
757.467, 780.423, 792.756, 701.685, 720.71, 677.292, 761.649, 
668.218, 679.042, 974.355, 1005.035, 1123.09, 1055.07, 1092.498, 
1100.654, 899.767, 1018.462, 1046.096, 1084.173, 1158.217, 802.194, 
276.773)), row.names = c(NA, -23L), class = "data.frame", .Names = c("Year", 
"Kcalpd", "Thtonnes"))
Run Code Online (Sandbox Code Playgroud)

并且,我的代码如下:

scaleFactor <- max(wfd$Thtonnes) / max(wfd$Kcalpd)

ggplot(wfd, aes(x=Year)) +
  geom_col(aes(y=Thtonnes), fill="blue") +
  geom_col(aes(y=Kcalpd * scaleFactor), fill="red") +
  scale_y_continuous(name="Thtonnes", sec.axis=sec_axis(~./scaleFactor, name="Kcalpd")) +
  theme(
    axis.title.y.left=element_text(color="blue"),
    axis.text.y.left=element_text(color="blue"),
    axis.title.y.right=element_text(color="red"),
    axis.text.y.right=element_text(color="red")
  )
Run Code Online (Sandbox Code Playgroud)

此代码改编自网站:Megatron 给出的Plot with 2 y axis,一个 y 轴在左侧,另一个 y 轴在右侧。此 Web 链接提供了一种在一张图中绘制条形图和线条图的良好解决方案。但是,它不会导致我在一张图中将两个不同比例的数据绘制为条形。因此,到目前为止,我已经达到了以下阶段。问题是我的酒吧一个接一个,如下图所示。我希望每年都将它们并排绘制。

见下图: 条形图图像

这个问题与我和 NortonGon 引用的链接完全不重复。不重复的原因如下: 1)没有绘制两个不同比例的条形图。大多数时候,这是通过分面来完成的。2)我已经证明可以绘制两个不同的条形图,而无需在两个不同的 y 轴上重新缩放。3)如果重复的标签被删除,那么我也会上传代码。

amb*_*aka 5

最终的答案和代码如下:

未重新缩放的 2-y 轴条形图

上图的代码如下,

A)数据

structure(list(Year = 1994:2016, Kcalpd = c(86L, 91L, 98L, 107L, 
116L, 126L, 123L, 112L, 103L, 102L, 103L, 92L, 77L, 59L, 43L, 
29L, 19L, 14L, 13L, 12L, 12L, 10L, 9L), Tonnes = c(728364, 757467, 
780423, 792756, 701685, 720710, 677292, 761649, 668218, 679042, 
974355, 1005035, 1123090, 1055070, 1092498, 1100654, 899767, 
1018462, 1046096, 1084173, 1158217, 802194, 276773)), row.names = c(NA, 
-23L), class = "data.frame", .Names = c("Year", "Kcalpd", "Tonnes"
))
Run Code Online (Sandbox Code Playgroud)

B) 代码

scaleFactor <- max(wfd$Thtonnes) / max(wfd$Kcalpd)

ggplot(wfd, aes(x=Year,  width=.4)) +
  geom_col(aes(y=Thtonnes), fill="blue", position = position_nudge(x = -.4)) +
  geom_col(aes(y=Kcalpd * scaleFactor), fill="red") +
  scale_y_continuous(name="Thtonnes (Rice + Wheat)", sec.axis=sec_axis(~./scaleFactor, name="Kcal per day")) +
  scale_x_continuous(breaks = seq(1994, 2016, 4)) +
  theme(
    axis.title.y.left=element_text(color="blue"),
    axis.text.y.left=element_text(color="blue"),
    axis.title.y.right=element_text(color="red"),
    axis.text.y.right=element_text(color="red")
  ) +
  labs(title = "Food Security in Venezuela, Cereals Production and Food Gap", x = element_blank())
Run Code Online (Sandbox Code Playgroud)

不涉及竞购交易。只需增加条之间的间隙并将一种类型移动该边距即可使它们并排对齐。