【问题标题】:Adding geom_rect to a geom_bar plot with a dataset containing factors使用包含因子的数据集将 geom_rect 添加到 geom_bar 图
【发布时间】:2021-06-07 20:07:13
【问题描述】:

我有一个数据集 (All_Rain_sub),它有一个位置名称和三个值 - 本月、昨天和过去三天的降雨量。我使用了 melt 函数创建了一个长数据集

All_Rain_melt<-melt(All_Rain_sub, id.vars = "station_name")

All_Rain_melt 具有以下结构:

$ station_name: Ord.factor w/ 129 levels "129. Main Office"<..: 129 128 127 126 125 124 123 122 121 120 ...
 $ variable    : Factor w/ 3 levels "yesterday","threeDay",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value       : num  0 0 0 0 0 0 0 0 0 0 ..

我使用下面的代码创建了一个条形图,这样 X 轴的顺序不会改变。原因是位置的排列顺序是先北后中后南:

All_Rain_melt$station_name<-factor(All_Rain_melt$station_name, levels = rev(unique(All_Rain_melt$station_name)), ordered = TRUE)

All_Rain_melt %>%
  arrange(-value) %>%
  ggplot(aes(x=station_name, y=value, fill=variable, width=0.5))+ 
  geom_bar(stat="identity", position = "identity")+coord_flip()+ 
  scale_y_continuous(expand = c(0,0), breaks = seq(0,4,by=0.5),limits = c(0,4),sec.axis = dup_axis())+
  theme(legend.position = "top", legend.key.height = unit(0.5,"cm"), legend.key.width = unit(2,"cm"),legend.title = element_blank(),
        panel.grid.major.x = element_line(color = "black", size = 0.5), panel.background = element_rect(fill = "white", color = "white"),
        axis.line = element_line(), axis.title = element_blank(),
        axis.text.y = element_text(size=5))

条形图看起来是我想要的方式,但现在我想为位置 1 到 30(位置 1 到 30 位于北部区域)、位置 31 到 63(中部)和位置 64 到 129(南部)添加 geom_rect ) 以不同的颜色。当我添加 geom_rect 时,ggplot 2 不会保持 X 轴的顺序并按字母顺序重新排序。有没有解决的办法?任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    了解您使用什么代码来添加 geom_rect 以了解它可能无法正常工作的原因会有所帮助。这是一个使用两种相关方法将geom_rect 绘制到 y 轴的数值的示例,这里是一个有序因子。

    annotate 语法对于一次性使用非常有用,而使用单独的 tibble 作为 geom_rect 的数据源可能是执行计算和组织更长的坐标集的好方法。

    library(tidyverse)
    mtcars %>%
      head() %>%
      rownames_to_column("car") %>%
      mutate(car = fct_reorder(car, wt)) %>%
      ggplot() +
      geom_col(aes( wt, car)) +
      annotate("rect", xmin = 0, xmax = 3, ymin = 0.5, ymax = 2.5, fill = "red", alpha = 0.2) +
      geom_rect(data = tibble(xmin = 0, xmax = 3.5, ymin = 2.5, ymax = 3.5),
                aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = "green", alpha = 0.2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2020-03-03
      • 1970-01-01
      相关资源
      最近更新 更多