gpt4 book ai didi

r - ggplot2,在 x 对数刻度上引入中断

转载 作者:行者123 更新时间:2023-12-05 03:02:13 26 4
gpt4 key购买 nike

我有这样一个情节:

 p<-ggplot() +
geom_line(data= myData, aes(x = myData$x , y = myData$y)) +
scale_x_log10()+
scale_y_log10()

我的 x 值为 seq(9880000, 12220000, 10000)

plot的x轴只有一个break,如果plot的x轴至少有3个break怎么办?

最佳答案

这是原始海报问题的完全可重现的示例,其中对数标度图仅在 x 轴上显示一个中断值。我在下面展示了三种可能的解决方案。

library(ggplot2)

# Create a reproducible example data.frame using R functions.
x = seq(9880000, 12220000, 10000)

# Use set.seed() so that anyone who runs this code
# will get the same sequence of 'random' values.
set.seed(31415)
y = cumsum(runif(n=length(x), min=-1e5, max=1e5)) + 1e6

dat = data.frame(x=x, y=y)

# Original poster's plot.
p1 = ggplot(data=dat, aes(x=x, y=y)) +
geom_line() +
scale_x_log10() +
scale_y_log10() +
labs(title="1. Plot has only one x-axis break.")

# Add extra x-axis breaks manually.
x_breaks = c(10^7.0, 10^7.04, 10^7.08)
p2 = ggplot(data=dat, aes(x=x, y=y)) +
geom_line() +
scale_x_log10(breaks=x_breaks) +
scale_y_log10() +
labs(title="2. Add some x-axis breaks manually.")


# Add extra x-axis breaks in semi-automated manner.
x_breaks = 10^pretty(log10(x))
x_labels = formatC(x_breaks, format = "e", digits = 2)
p3 = ggplot(data=dat, aes(x=x, y=y)) +
geom_line() +
scale_x_log10(breaks=x_breaks, labels=x_labels) +
scale_y_log10() +
labs(title="3. Create x-axis breaks with R functions.")



# Skip the log10 scale because the x-values don't span multiple orders of magnitude.
p4 = ggplot(data=dat, aes(x=x, y=y)) +
geom_line() +
scale_y_log10() +
labs(title="4. Check appearance without log10 scale for x-axis.")


library(gridExtra)
ggsave("example.png", plot=arrangeGrob(p1, p2, p3, p4, nrow=2),
width=10, height=5, dpi=150)

enter image description here

关于r - ggplot2,在 x 对数刻度上引入中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113333/

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