[英]How to rotate the legend labels to match the orientation in the plot?
图例标签是垂直方向的,但在调用coord_flip()
之后,我希望它们是水平方向的。
我怎样才能解决这个问题?
library(ggplot2)
tbl <- structure(
list(
ppm_id = c(
"PPM000001",
"PPM000002",
"PPM000014",
"PPM000015",
"PPM000050",
"PPM000051",
"PPM000084",
"PPM000085"
),
estimate_type_long = c(
"Odds Ratio",
"Odds Ratio",
"Hazard Ratio",
"Hazard Ratio",
"Hazard Ratio",
"Hazard Ratio",
"Hazard Ratio",
"Relative Risk "
),
estimate = c(1.55, 1.63, 1.21, 1.14, 1.17,
1.24, 1.17, 1.2),
interval_lower = c(1.52, 1.6, 1.17, 1.02, 1.13,
1.15, 1.01, 1.05),
interval_upper = c(1.58, 1.67, 1.26, 1.28,
1.21, 1.34, 1.34, 1.38)
),
row.names = c(NA, -8L),
class = c("tbl_df",
"tbl", "data.frame")
)
ggplot(data = tbl,
aes(
x = ppm_id,
y = estimate,
ymin = interval_lower,
ymax = interval_upper,
col = estimate_type_long
)) +
geom_pointrange() +
geom_hline(yintercept = 1, lty = 2) + # add a dotted line at x=1 after flip
coord_flip() + # flip coordinates (puts labels on y axis)
xlab("Label") + ylab("Mean (95% CI)") +
theme_bw() # use a white background
由代表 package (v2.0.0) 于 2021 年 5 月 21 日创建
一种解决方法是使用点和误差线图层而不是geom_pointrange()
。 误差线具有水平线键字形,其中点范围在键中有垂直线。
在geom_errorbar()
中使用width = 0
来消除末端条。 您需要在此处调整点大小以使它们“更胖”(pointrange 层对此有一个fatten
参数); 我认为size = 2
看起来很接近。
ggplot(data = tbl,
aes(
x = ppm_id,
y = estimate,
ymin = interval_lower,
ymax = interval_upper,
col = estimate_type_long
)) +
geom_point(size = 2) +
geom_errorbar(width = 0) +
# geom_pointrange() +
geom_hline(yintercept = 1, lty = 2) + # add a dotted line at x=1 after flip
coord_flip() + # flip coordinates (puts labels on y axis)
xlab("Label") + ylab("Mean (95% CI)") +
theme_bw() # use a white background
由代表 package (v2.0.0) 于 2021 年 5 月 21 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.