我想绘制连续变量和分类变量(geom_boxplotwith ggplot2)之间关系的箱线图,这适用于几种情况(facet_wrap)。很简单:
data("CO2")
ggplot(CO2, aes(Treatment, uptake) ) +
geom_boxplot(aes(Treatment, uptake),
col="black", fill="white", alpha=0, width=.5) +
geom_point(col="black", size=1.2) +
facet_wrap(~Type, ncol=3, nrow=6, scales= "free_y") +
theme_bw() +
ylab("Uptake")
Run Code Online (Sandbox Code Playgroud)
This is quite nice with this toy dataset, but applied to my own data (where facet_wrap enables me to plot 18 different graphs) the y-axes are hardly readable, with varying number of y-ticks and varying spacing between them:
What could be a nice way to harmonize the y-axes? (i.e., getting equal spacing between y-axes ticks, no matter what breaks are -these will necessarily change from a graph to another because the variation range of my continuous variable changes a lot)
Thank you very much for any help :)
您可以通过pretty()在 y 轴上应用y 轴值并获取第一个/最后一个值来手动扩展每个方面的值,从而将强制每个方面的限制转为看起来相对漂亮的东西。
以下是使用钻石数据集的示例:
# normal facet_wrap plot with many different y-axis scales across facets
p <- ggplot(diamonds %>% filter(cut %in% c("Fair", "Ideal")),
aes(x = cut, y = carat) ) +
geom_boxplot(col="black", fill="white", alpha=0, width=.5) +
geom_point(col="black", size=1.2) +
facet_wrap(~clarity, scales= "free_y", nrow = 2) +
theme_bw() +
ylab("Uptake")
p
Run Code Online (Sandbox Code Playgroud)
# modified plot with consistent label placements
p +
# Manually create values to expand the scale, by finding "pretty"
# values that are slightly larger than the range of y-axis values
# within each facet; set alpha = 0 since they aren't meant to be seen
geom_point(data = . %>%
group_by(clarity) %>% #group by facet variable
summarise(y.min = pretty(carat)[1],
y.max = pretty(carat)[length(pretty(carat))]) %>%
tidyr::gather(key, value, -clarity),
aes(x = 1, y = value),
inherit.aes = FALSE, alpha = 0) +
# Turn off automatical scale expansion, & manually set scale breaks
# as an evenly spaced sequence (with the "pretty" values created above
# providing the limits for each facet). If there are many facets to
# show, I recommend no more than 3 labels in each facet, to keep things
# simple.
scale_y_continuous(breaks = function(x) seq(from = x[1],
to = x[2],
length.out = 3),
expand = c(0, 0))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
904 次 |
| 最近记录: |