【发布时间】:2021-01-06 12:35:41
【问题描述】:
我正在尝试使用ggplot2 在bar plot 和double-y-axis 上绘制line graph。
以下是条形图的示例数据和代码:
library(ggplot2)
data <- data.frame("groups" = c('AA','BB','CC', 'AA','BB','CC', 'AA','BB','CC'),
"something" = c('aaaaaa', 'bbbbb', 'cccccc', 'dddddddd', 'eeeeeee', 'ffffffff', 'gggggggggg', 'hhhhhhhhh', 'iiiiiiiii'),
"value1" = c(1.1, 2.4, 3.5, 5, 4.1, 3, 2.5, 1.4, 4.5),
"value2" = c(2, 25, 10, 4, 15, 5, 3, 4, 8))
p1 <- ggplot(data, aes(x = something,
y = value1,
fill = groups)) + geom_bar(stat = "identity", position = "dodge") +
xlab("something") + ylab("groups") + labs(fill = "groups") +
theme_bw() + theme(aspect.ratio = 2/1,
axis.title.x = element_text(face="bold"),
axis.title.y = element_text(face="bold"),
axis.text.x = element_text(angle = 90, vjust = 0.2, hjust=1)) + coord_equal(1/0.2)
我正在尝试将line 添加到上述bar chart。但是,y-axis 两边的scale 显示相同。
p1 + geom_line(aes(x = something, y = value2), size = 1, color="red", group = 1) +
scale_y_continuous(sec.axis = sec_axis(~., name = "Count")) +
geom_point(aes(x = something, y = value2), size = 1, color="blue", group = 1) +
theme(axis.line.y.right = element_line(color = "red"),
axis.ticks.y.right = element_line(color = "red"),
axis.text.y.right = element_text(color = "red"),
axis.title.y.right = element_text(color = "red"))
当我试图操纵y 值时,如biostats 所示。但是,我仍然没有得到正确的line、bars 和values。
p1 + geom_line(aes(x = something, y = 0.1*value2), size = 1, color="red", group = 1) +
scale_y_continuous(sec.axis = sec_axis(~./0.1, name = "Count")) +
geom_point(aes(x = something, y = 0.1*value2), size = 1, color="blue", group = 1) +
theme(axis.line.y.right = element_line(color = "red"),
axis.ticks.y.right = element_line(color = "red"),
axis.text.y.right = element_text(color = "red"),
axis.title.y.right = element_text(color = "red"))
我想为每个对应的axis 绘制正确的line 和bar。
【问题讨论】:
-
你对这个情节到底有什么问题?对我来说,你的情节和 sec 轴看起来不错。 sec 轴的范围从 0 到 50,并显示
value2的正确比例。