R语言 ggplot2图的填充区域是否可以更改以匹配每个x轴坐标处的值

oknwwptz  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(126)

我有以下 Dataframe 。

S <- rep(c("A","B","C"), each = 30)
Y <- rep(c("X", "Y", "Z"), 30)
V <- as.factor(runif(90, min=0, max=100))
df <- as.data.frame(cbind(S, Y, V))
df$V <- as.numeric(V)

我把它标绘如下。

ggplot(data = df, aes(x = Y, 
                      y = V, group = 1, fill=V)) +
  geom_line(linewidth=3) +
  theme_classic()+
  labs(title="",
       x=paste(""),
       y=paste(""),
  )+
  theme(plot.title=element_text(size=18, face="bold",hjust = 0.7, vjust=0.2,
                                margin = margin(t = 0, r = 10, b = 10, l = 0)),
        axis.text.x=element_text(size=14, face="bold", angle=90),
        axis.text.y=element_blank(),
        axis.title.x=element_text(size=16, face="bold",
                                  margin = margin(t = 10, r = 0, b = 0, l = 0)),
        axis.title.y=element_blank(),
        legend.text=element_text(size=14, face="bold"),
        legend.title =element_text(size=14, face="bold"))+
  facet_wrap(~ S, ncol= 1, strip.position="left")+
  geom_area()+
  scale_fill_gradient(low="blue", high="red")

有没有一种方法可以让区域颜色根据V的值而改变。目前的图看起来是这样的,但我希望值在图经过每个X坐标时都能对应。

pengsaosao

pengsaosao1#

我通常会通过插入数百个值并为每个值设置单独的列来完成此操作。因为您有一个离散轴,所以必须将其转换为数值,然后使用scale_x_continuous再次使其看起来离散

library(tidyverse)

df %>%
  group_by(S) %>%
  mutate(Y = factor(Y)) %>%
  summarize(xval = seq(1, nlevels(Y), length.out = 500),
            yval = approx(as.numeric(Y), V, ties = "ordered", xout = xval)$y,
            Y = levels(Y)[floor(xval)], .groups = "drop") %>%
  ggplot(aes(xval, yval, fill = yval)) +
  geom_col(width = 0.01, position = "identity") +
  geom_line(linewidth = 1) +
  facet_wrap(~ S, ncol = 1, strip.position = "left") +
  scale_fill_gradient(low = "blue", high = "red") +
  scale_x_continuous(breaks = seq(length(unique(df$Y))),
                     labels = unique(df$Y), expand = c(0, 0.5, 0, 0.5)) +
  labs(x = NULL, y = NULL, fill = "V") +
  theme_classic(base_size = 14) +
  theme(axis.text.x = element_text(face = "bold", angle = 90),
        axis.text.y = element_blank(),
        legend.text = element_text(face = "bold"),
        legend.title = element_text(face = "bold"))

相关问题