R根据变量重新缩放第二个Y轴

R rescale 2nd Y-axis according to a variable

我一直在尝试将直方图和折线图合二为一。直方图是抗生素处方的确切数量(左 y 轴)。折线图是抗生素使用量的百分比(右轴)。到目前为止,我已经将它们合并在一起,将右轴向右移动,但右 y 轴使用与左轴相同的比例。直方图和折线图的尺度当然是非常非常不同的。

我的问题开始之前的一些信息:

我现在的代码是:

  ggplot(Grafiek3, aes(x = Jaren, y =n_fosfo)) + #samenvoegen
geom_bar(stat="identity", fill="#69b3a2" ) +
scale_x_continuous(labels = as.character(Grafiek3$Jaren), breaks = Grafiek3$Jaren) +
xlab ("Year") +
theme(plot.title = element_text(hjust = 0.5)) +
ggtitle("Increase fosfomycin prescriptions per year")+
geom_line(aes(x=Jaren, y=per_fos), color="black") +
geom_point(aes(x=Jaren, y=per_fos), shape=21, color="black", fill="#69b3a2", size=2) +
scale_y_continuous(
  name = expression("Total amount of prescriptions"), 
  sec.axis = sec_axis(~., name = "Percentage")) +
theme(plot.title = element_text(hjust = 0.5)) +
ggtitle("Percentage of fosfomycin prescriptions per year")

输出如下: Unfinished graph

如图所示,折线图位于底部,但看起来应该是这样的:

  ggplot(Grafiek3, aes(x=Jaren, y =per_fos)) + #line graph
  geom_line(color="grey") +
  geom_point(shape=21, color="black", fill="#69b3a2", size=2) +
  scale_x_continuous(labels = as.character(Grafiek3$Jaren), breaks = Grafiek3$Jaren) +
  scale_y_continuous(position = "right") +
  xlab ("Year") +
  ylab ("Percentage") +
  theme(plot.title = element_text(hjust = 0.5)) +
  ggtitle("Percentage of fosfomycin prescriptions per year")

图片: Line graph

我看到更改代码:

sec.axis = sec_axis(~., name = "Percentage"))

变成这样的东西:

sec.axis = sec_axis(~./42, name = "Percentage"))

会修复它,但不幸的是,这只会改变右轴,但线图不会随之移动。

那么,有没有人知道如何将折线图(图片)移动到直方图中?或者如何更改右轴,使其使用 "per_fos" 变量的信息?

构建了可以使用的数据集:

years <- c(2013, 2014, 2015, 2016, 2017, 2018, 2019)
amount <- c(120, 150, 200, 170, 180, 240, 80)
percentage <- c(5.4, 5.9, 6.3, 7.1, 7.8, 8.4, 10.4)
df <- data.frame(years, amount, percentage)

只是想让你知道,两个不同比例的 y 轴不是好的做法。这就是为什么用 ggplot2 做你想做的事情并不容易。 请参阅此 link 以获得关于该问题的良好讨论:ggplot with 2 y axes on each side and different scales



library(ggplot2)
library(dplyr)
library(scales)


years <- c(2013, 2014, 2015, 2016, 2017, 2018, 2019)
amount <- c(120, 150, 200, 170, 180, 240, 80)
percentage <- c(5.4, 5.9, 6.3, 7.1, 7.8, 8.4, 10.4)

df <- data.frame(years, amount, percentage)
# create a modified percentage column to fit in with the scale of the columns:

df <- 
  df %>% 
  mutate(pc_rescale = rescale(percentage, to = c(20, 200)))

# plot and add suitable labels; if you want the labels scaled evenly you need to unpick the rescaling function. 

ggplot(df, aes(years, amount)) +
  geom_col()+
  geom_line(aes(years, pc_rescale))+
  scale_y_continuous(sec.axis = sec_axis(~., labels = df$percentage, breaks = df$pc_rescale, name = "Percentage" ))

reprex package (v0.3.0)

于 2020-05-21 创建