gpt4 book ai didi

r - 我可以精确限制ggplot轴范围吗?

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

在ggplot图表中,我想在副轴上重新缩放y,以使最小y值等于0,最大y值等于100。
我这样尝试过:

mydata <- data.frame(x = c(0, 1, 2, 3, 4, 5), 
y = c(20, 55, 69, 72, 73, 72))
break2 <- seq(0, 100, 10)

library(ggplot2)

ggplot(data = mydata, aes(x = x, y = y)) +
ylim(20, 73) +
geom_point(shape = 21, size = 5, color = "black", fill = "orange", stroke = 1) +
scale_x_continuous(name = 'Number of Contacts') +
scale_y_continuous(name = "Remembered (%)",
sec.axis = sec_axis(trans = ~ (.-min(.)) * 100 / (max(.) - min(.)),
name = "Remembered (Index)",
breaks = break2))

可以看出,ggplot忽略了y限制为20-73的事实。它以较低的值开始,以左侧的较高值结束。因此,右侧的辅助轴错误地重新缩放: y=20对应于> 0的重新缩放值。而且, y=73不符合预期的100。

可以将y轴范围扩大,但是右侧的0应该从y的最小值20开始。

有办法解决吗?还是有更好的方法来做到这一点?

最佳答案

正如Axeman指出的那样,在limits中指定scale_y_continuous()将限制y轴。另一种选择是将coord_cartesian(ylim = c(20, 73))添加到您的代码中。

两者之间的区别(与geom_point不相关)是scale_y_continuous(limits = c(...))会限制传递给ggplot进行绘图的值的范围,而coord_cartesian(ylim = c(...))会在绘制所有内容后限制可见范围。

RStudio的ggplot2 package cheatsheet很好地总结了这一点:

illustration

至于在面板的边缘处切掉一些点的问题,可以通过将绘图转换为grob并关闭面板的剪裁来解决:

# plot with restricted range
p <- ggplot(data = mydata, aes(x = x, y = y)) +
geom_point(shape = 21, size = 5, color = "black", fill = "orange", stroke = 1) +
scale_x_continuous(name = 'Number of Contacts') +
scale_y_continuous(name = "Remembered (%)",
expand = c(0, 0),
sec.axis = sec_axis(trans = ~ (.-min(.))*100/(max(.)-min(.)),
name = "Remembered (Index)",
breaks = break2)) +
coord_cartesian(ylim = c(20, 73)) +
theme(plot.margin = margin(t = 10, unit = "pt")) # increase top margin as some points
# are very close to the top edge

# convert to grob
gp <- ggplotGrob(p)

grid::grid.draw(gp) # verify that the points at the edge are cut off

# turn off clipping for panel
gp$layout$clip[gp$layout$name=="panel"] <- "off"

grid::grid.draw(gp) # points at the edge are now visible

plot

关于r - 我可以精确限制ggplot轴范围吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524474/

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