我正在使用 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)
并且输出是这样的:
但是,我想给低密度曲线着色,然后像这样更改代码:
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")
我得到了这样的输出:
这并不理想,所以我尝试使用以下代码设置刻度线间隔:
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))
变正常了但是颜色没了是这样的:
谁能帮我解决这个错误?谢谢。
如果您使用 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