r - ggplot2 中刻度线间隔和密度曲线的错误

标签 r ggplot2

<分区>

我正在使用 ggplot2 使用以下 R 代码绘制折线图:

library(ggplot2)

X <-c(0, 1, 2, 3, 4,  5)
Y <-c(1, 2, 3, 2, 1, 2)
df <- data.frame(X=X, Y=Y)

ggplot(data=df, mapping=aes(x=X, y=Y))+
  geom_line(colour="violet", size=3, linetype=2)+
  geom_point(shape=23, fill="blue", color="darkred", size=3)

并且输出是这样的:

enter image description here

但是,我想给低密度曲线着色,然后像这样更改代码:

ggplot(data=df, mapping=aes(x=X, y=Y))+geom_line(colour="violet", size=3, linetype=2)+geom_point(shape=23, fill="blue", color="darkred", size=3)+geom_area("darkseagreen1")

我得到了这样的输出:

enter image description here

这并不理想,所以我尝试使用以下代码设置刻度线间隔:

ggplot(data=df, mapping=aes(x=X, y=Y))+geom_line(colour="violet", size=3, linetype=2)+geom_point(shape=23, fill="blue", color="darkred", size=3)+geom_area(fill = "darkseagreen1")+scale_y_continuous(breaks = seq(71.4, 72.9, by=0.3), limits=c(71.4,72.7))

变正常了但是颜色没了是这样的:

enter image description here

谁能帮我解决这个错误?谢谢。

最佳答案

如果您使用 coord_cartesian() 设置限制,则可以使用 geom_area()(有关详细信息,请参阅 https://stackoverflow.com/a/3606798/12957340)。

例如:

library(ggplot2)

X <-c(0, 1, 2, 3, 4,  5)
Y <-c(1, 2, 3, 2, 1, 2)
df <- data.frame(X=X, Y=Y)

# starting plot
ggplot(data=df, mapping=aes(x=X, y=Y)) +
  geom_line(colour="violet", size=3, linetype=2) +
  geom_point(shape=23, fill="blue", color="darkred", size=3)
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.

ggsave("example.pdf")
#> Saving 7 x 5 in image

# with geom_area()
ggplot(data=df, mapping=aes(x=X, y=Y)) +
  geom_line(colour="violet", size=3, linetype=2) +
  geom_point(shape=23, fill="blue", color="darkred", size=3) +
  geom_area(fill = "darkseagreen1")

ggsave("example2.pdf")
#> Saving 7 x 5 in image

# add y-axis limits (the problem)
ggplot(data=df, mapping=aes(x=X, y=Y)) +
  geom_line(colour="violet", size=3, linetype=2) +
  geom_point(shape=23, fill="blue", color="darkred", size=3) +
  geom_area(fill = "darkseagreen1") +
  scale_y_continuous(breaks = seq(0, 3, by=0.3), limits = c(1, 2))

ggsave("example3.pdf")
#> Saving 7 x 5 in image

# add y-axis limits without losing data (a solution)
ggplot(data=df, mapping=aes(x=X, y=Y)) +
  geom_line(colour="violet", size=3, linetype=2) +
  geom_point(shape=23, fill="blue", color="darkred", size=3) +
  geom_area(fill = "darkseagreen1") +
  scale_y_continuous(breaks = seq(0, 3, by=0.3)) +
  coord_cartesian(ylim = c(1,2))

ggsave("example4.pdf")
#> Saving 7 x 5 in image

创建于 2023-02-08 reprex v2.0.2

关于r - ggplot2 中刻度线间隔和密度曲线的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75347864/

相关文章:

r - 如何使用 R 动态回归和预测多个项目?

r - 在 ggplot2 中使用 `facet_grid` 时突出显示/在一些图周围画一个框

R从多列绘制x轴标签

python - 开始使用简单的 pymc3 示例时遇到麻烦

r - 绑定(bind)许多数据框,添加一个带有其 id 的列

r - 如何将集合变成集合成员的指标?

R 的集群包中 daisy() 的 Python 等价物

R ggplot2 - geom_point 自定义颜色范围和颜色

r - 针对 x 和 y 轴绘制第三个变量

r - 打印一些 HEX 颜色以查看它们