【发布时间】: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 轴的顺序并按字母顺序重新排序。有没有解决的办法?任何帮助将不胜感激。谢谢。
【问题讨论】: