【发布时间】:2018-02-28 18:06:56
【问题描述】:
我有一个使用 geom_bar() 的条形图,我想使用 geom_point() 覆盖点。问题是轴标签的顺序。我有 2 个组,我想用 geom_bar() 从高到低排序的组 A 和我想用 geom_bar 的点显示的组 B。 A 组和 B 组并不总是具有相同的类别,但我总是希望 A 组显示有条形并从高到低排序。和
如果您运行此代码,您将看到正确排列的条形图。我需要先显示宠物超类别,然后再显示汽车类别。我已将超类别定义为有序因子并且它正在工作。
然后在超类别中,条形按组 A 的值从高到低排序。你可以看到在宠物类别中狗比其他人高,起亚在汽车类别中比其他人高。
library(dplyr)
group = c("A","A","A","B","B","B","A","A","A","B","B","B")
supercategory = c("pet", "pet","pet","pet","pet","pet","car","car","car","car","car","car")
category = c("bird","cat","dog","bird","cat","lizard","ford","chevy","kia","kia","toyota","ford")
supercategory = factor(supercategory, levels= c("pet", "car"), ordered = TRUE)
value=c(3,4,5,4,5,6,1,3,10,8,3,5)
dat = data.frame(group = group,supercategory = supercategory, category = category, value = value )
dat = dat %>% mutate(LABEL = paste0(supercategory, "-",category), HIGH_VALUE = ifelse(group =="A",value,0)) %>%
arrange(supercategory, -HIGH_VALUE)
# after the lines above the data is ordered correctly. first by supercategory then by group A's value from higest to lowest using the HIGH_VALUE field
dat$ROW_NUMBER = 1:nrow(dat)
dat = dat %>% group_by(supercategory,category) %>% mutate(ROW_NUMBER2= min(ROW_NUMBER)) %>% arrange( supercategory ,ROW_NUMBER2)
# after the 2 lines above now the data is sorted by ROW_NUMBER2 which orders the category within supercategory.
# Group A will be be in bars using geom_bar
# group B will be displayed iwht points using geom_point
# The bars and points should be in the order of ROW_NUMBER2
library(ggplot2)
dat$LABEL = factor(dat$LABEL, levels = unique(dat$LABEL), ordered = TRUE)
ggplot(dat[dat$group=="A",] , aes(x = LABEL, y = value))+
geom_bar(stat="identity")
我想保持上面图的顺序,只需在条形上方添加点。如果 B 组有一个不属于 A 组的类别,则该点应位于 A 组在其所在超类别中的最后一个小节的右侧。
但是当我尝试添加点时,排序会变得混乱。运行这段代码,它只是将 B 组的数据添加为点,你会看到标签的顺序被弄乱了。
library(ggplot2)
dat$LABEL = factor(dat$LABEL, levels = unique(dat$LABEL), ordered = TRUE)
ggplot(dat[dat$group=="A",] , aes(x = LABEL, y = value))+
geom_bar(stat="identity") +
geom_point(data = dat[dat$group=="B",], aes(x = LABEL, y = value), shape=15, size = 3, color = "blue" )
如何将这条线添加到情节中:
geom_point(data = dat[dat$group=="B",], aes(x = LABEL, y = value), shape=15, size = 3, color = "blue" )
同时保持 A 组的排序?
【问题讨论】:
-
我们的回答有帮助吗?