gpt4 book ai didi

r - 在 ggplot2 中手动为 x 和 y Axis 添加中断

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

我通常使用 scale_y_continuous(或 scale_x_continuous)更改 ggplot2 中连续变量的比例中断。我通常还使用 coord_cartesian(xlim=) (或 ylim= 用于 y Axis )设置 Axis 限制。所有这些都可以正常工作,如下所示:

#Some example data
set.seed(100)
b<-sample(1:10, 10)
a<-sample(1:10, 10)

df<-data.frame(a,b)

#Graph without scales set (just default)
library(ggplot2)
ggplot(data=df, aes(a,b))+
theme_bw() + theme(panel.border = element_rect(colour = "black", fill=NA, size=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"))+
geom_text(aes(label=rownames(df)), color="black")

这会产生以下具有默认比例的图:

enter image description here

如果我想将 x Axis 调整为 1-13(即从 1 开始到 13 结束的 13 个刻度线),我会执行以下操作:

ggplot(data=df, aes(a,b))+
theme_bw() + theme(panel.border = element_rect(colour = "black", fill=NA, size=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"))+
geom_text(aes(label=rownames(df)), color="black")+
scale_x_continuous(breaks = c(1,3,5,7,9,11,13))+
coord_cartesian(xlim=c(0, 13))

enter image description here

...对于 y Axis ...

ggplot(data=df, aes(a,b))+
theme_bw() + theme(panel.border = element_rect(colour = "black", fill=NA, size=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"))+
geom_text(aes(label=rownames(df)), color="black")+
scale_y_continuous(breaks = c(1,3,5,7,9,11,13))+
coord_cartesian(ylim=c(0, 13))

enter image description here

但是,当我尝试同时对两个轴进行相同的比例调整时,输出不会产生我期望的结果(x Axis 和 y Axis 上都是 1-13)。

ggplot(data=df, aes(a,b))+
theme_bw() + theme(panel.border = element_rect(colour = "black", fill=NA, size=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"))+
geom_text(aes(label=rownames(df)), color="black")+
scale_y_continuous(breaks = c(1,3,5,7,9,11,13))+
coord_cartesian(ylim=c(0, 13))+
scale_x_continuous(breaks = c(1,3,5,7,9,11,13))+
coord_cartesian(xlim=c(0, 13))

enter image description here

如您所见,即使将完全相同的代码传递给两个轴,x Axis 和 y Axis 也不等价。我不明白为什么。非常感谢任何帮助。

最佳答案

set.seed(100)
df <- data.frame(b = sample(1:10, 10), a = sample(1:10, 10))


ggplot(data=df, aes(a,b))+
theme_bw() + theme(panel.border = element_rect(colour = "black", fill=NA, size=1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")) +
geom_text(aes(label=rownames(df)), color="black") +
scale_y_continuous(breaks = c(1,3,5,7,9,11,13)) +
scale_x_continuous(breaks = c(1,3,5,7,9,11,13)) +
coord_fixed(ylim=c(0, 13),xlim=c(0, 13))

enter image description here

关于r - 在 ggplot2 中手动为 x 和 y Axis 添加中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39157508/

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