使用这个假人 data.frame
ts <- data.frame(x=1:3, y=c("blue", "white", "white"), z=c("one", "one", "two"))
Run Code Online (Sandbox Code Playgroud)
我尝试用顶部的"蓝色"类别绘图.
ggplot(ts, aes(z, x, fill=factor(y, levels=c("blue","white" )))) + geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
给我"白色"在上面.和
ggplot(ts, aes(z, x, fill=factor(y, levels=c("white", "blue")))) + geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
颠倒颜色,但仍然让我在上面"白色".我怎样才能获得"蓝色"?
Inh*_*ant 47
对于它的价值,在ggplot2版本2.2.1中,堆栈的顺序不再由data.frame中的行顺序决定.相反,它匹配图例的顺序,由图例中的级别顺序确定.
d <- data.frame(
y=c(0.1, 0.2, 0.7),
cat = factor(c('No', 'Yes', 'NA'), levels = c('NA', 'Yes', 'No')))
# Original order
p1 <- ggplot(d, aes(x=1, y=y, fill=cat)) +
geom_bar(stat='identity')
# Change order of rows
p2 <- ggplot(d[c(2, 3, 1), ], aes(x=1, y=y, fill=cat)) +
geom_bar(stat='identity')
# Change order of levels
d$cat2 <- relevel(d$cat, 'Yes')
p3 <- ggplot(d, aes(x=1, y=y, fill=cat2)) +
geom_bar(stat='identity')
grid.arrange(p1, p2, p3, ncol=3)
Run Code Online (Sandbox Code Playgroud)
Her*_*oka 46
我之前一直在努力解决同样的问题.似乎ggplot根据它们在数据框中的外观来堆叠条形图.因此,您的问题的解决方案是按照您希望它显示在图例中的相反顺序的填充因子对数据进行排序:数据框顶部的底部项目和底部的顶部项目:
ggplot(ts[order(ts$y, decreasing = T),],
aes(z, x, fill=factor(y, levels=c("blue","white" )))) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
使用样本数据,我创建了三个具有不同数据帧顺序的图,我认为更多的填充变量会使事情变得更清晰.
set.seed(123)
library(gridExtra)
df <- data.frame(x=rep(c(1,2),each=5),
fill_var=rep(LETTERS[1:5], 2),
y=1)
#original order
p1 <- ggplot(df, aes(x=x,y=y,fill=fill_var))+
geom_bar(stat="identity") + labs(title="Original dataframe")
#random order
p2 <- ggplot(df[sample(1:10),],aes(x=x,y=y,fill=fill_var))+
geom_bar(stat="identity") + labs(title="Random order")
#legend checks out, sequence wird
#reverse order
p3 <- ggplot(df[order(df$fill_var,decreasing=T),],
aes(x=x,y=y,fill=fill_var))+
geom_bar(stat="identity") + labs(title="Reverse sort by fill")
plots <- list(p1,p2,p3)
do.call(grid.arrange,plots)
Run Code Online (Sandbox Code Playgroud)
为了使图表看起来更漂亮而使用数据似乎是个坏主意。这是使用时对我有用的替代方法position_fill():
ggplot(data, aes(x, fill = fill)) + geom_bar(position = position_fill(reverse = TRUE))
Run Code Online (Sandbox Code Playgroud)
该reverse = TRUE参数翻转堆叠条的顺序。这position_stack也适用。
小智 6
我今天遇到了完全相同的问题.您可以blue使用order=-as.numeric()以下方式获得最佳效果:
ggplot(ts,
aes(z, x, fill=factor(y, levels=c("blue","white")), order=-as.numeric(y))) +
geom_bar(stat = "identity")
Run Code Online (Sandbox Code Playgroud)
小智 6
group在ggplot()通话中使用aethetic .这可确保以相同方式堆叠所有层.
series <- data.frame(
time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)),
type = rep(c('a', 'b', 'c', 'd'), 4),
value = rpois(16, 10)
)
ggplot(series, aes(time, value, group = type)) +
geom_col(aes(fill = type)) +
geom_text(aes(label = type), position = "stack")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55159 次 |
| 最近记录: |