gpt4 book ai didi

r - 如何显示比例 (0-1) 条形图以及具有不同轴的线数据?

转载 作者:行者123 更新时间:2023-12-05 05:30:21 26 4
gpt4 key购买 nike

我有三批数据要一起绘制:两个 geom_line() 在一个堆叠的 geom_bar() 之上。所有这些都在一个时间序列上,每年都有一个条形图和两条线值。数据看起来像这样:

df <- data.frame(year = rep(1:5, each = 3),
cat = c("small", "med", "large"),
count = rep(sample(1:10, 5)),
line1 = rep(sample(30000:40000, 5), each = 3),
line2 = rep(sample(200:300, 5), each = 3))

将所有三个绘制在一起很容易,但我不想显示条形的 y 轴标签。相反,我希望左轴显示一条线,右轴显示另一条线。我希望情节看起来像这样:

like this

但要让左轴显示 line1 值(即 30000:40000 值)。我将如何着手包括两个线轴,但仍显示横跨绘图整个高度的条形?

library(ggplot2)
ggplot(data = df, aes(x=year)) +
geom_bar(aes(y = count, x = year, fill = cat), position = "fill", stat="identity") +
geom_line(aes(y = line1/max(line1))) +
geom_line(aes(y = line2/max(line2)), color = "red") +
scale_y_continuous(sec.axis = sec_axis(~.*max(df$line2), name = "line2 (red)"))

在两轴线图后简单地添加 geom_bar() 会导致条形图不显示,因为线条数据的比例远远超出比例 (0-1) 条形图数据的比例:

ggplot(data = df, aes(x=year)) +
geom_line(aes(y = line1)) +
geom_line(aes(y = line2*100), color = "red") +
scale_y_continuous(sec.axis = sec_axis(~./100, name = "line2 (red)")) +
geom_bar(aes(y = count, x = year, fill = cat), position = "fill", stat="identity")

我想要这些轴,但仍然显示条形图:

最佳答案

可以通过在线 dplyr 计算来完成:

library(dplyr); library(ggplot2)
ggplot(data = df, aes(x=year)) +
geom_col(data = df %>% group_by(year) %>%
mutate(share = count / sum(count) * max(df$line1)),
aes(y = share, x = year, fill = cat)) +
geom_line(aes(y = line1)) +
geom_line(aes(y = line2*100), color = "red") +
scale_y_continuous(sec.axis = sec_axis(~./100, name = "line2 (red)"))

enter image description here

关于r - 如何显示比例 (0-1) 条形图以及具有不同轴的线数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74725175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com