【发布时间】:2016-08-27 11:16:13
【问题描述】:
我想在保持秩序的同时创建分组条形图。如果它是单列而不是分组条形图,则使用重新排序功能是显而易见的。但不确定如何在融化的 data.frame 上使用它。
下面是代码示例的详细解释:
假设我们有以下 data.frame:
d.nfl <- data.frame(Team1=c("Vikings", "Chicago", "GreenBay", "Detroit"), Win=c(20, 13, 9, 12))
在翻转时绘制一个简单的条形图。
ggplot(d.nfl, aes(x = Team1, y=Win)) + geom_bar(aes(fill=Team1), stat="identity") + coord_flip()
上面的情节没有订单,如果我想通过 win 来订购情节,我可以执行以下操作:
d.nfl$orderedTeam <- reorder(d.nfl$Team1, d.nfl$Win)
ggplot(d.nfl, aes(x = orderedTeam, y=Win)) + geom_bar(aes(fill=orderedTeam), stat="identity") + coord_flip()
现在假设我们添加另一列(到原始数据框)
d.nfl$points <- c(12, 3, 45, 5)
Team1 Win points
1 Vikings 20 12
2 Chicago 13 3
3 GreenBay 9 45
4 Detroit 12 5
要生成分组条形图,首先我们需要将其融化:
library(reshape2)
> d.nfl.melt <- melt(d.nfl[,c('Team1','Win','points')],id.vars = 1)
> ggplot(d.nfl.melt,aes(x = Team1,y = value)) + geom_bar(aes(fill = variable),position = "dodge", stat="identity") + coord_flip()
ggplot 上面是无序的。
但是我如何做有序组条形图(升序方式)
【问题讨论】:
-
您第一次对因子水平进行了重新排序,并且成功了。也许尝试在融化的数据框上设置因子级别顺序...?
-
一些相关的here。使用堆叠,您只需要在绘图之前对数据集进行排序,但这似乎不适用于躲避。
-
@joran 试过没用:
> melted.theTable <- within(d.nfl.melt, Team1 <- factor(Team1, levels = names(sort(table(Team1), decreasing=FALSE)))) > ggplot(melted.theTable,aes(x = Team1,y = value)) + geom_bar(aes(fill = variable),position = "dodge", stat="identity") + coord_flip() -
重新检查您设置级别顺序的尝试;这是错误的。