ggplot2:如何绘制条形图,其中条形图表示百分比并根据百分比值着色?

时间:2016-02-15 22:15:19

标签: r ggplot2

我需要制作一个特定类型的条形图,我需要使用ggplot2 - 可悲的是我对这个软件包知之甚少 - 我今天开始学习它。

我有这样的数据框:

name <- letters[1:10]
percentage <- c(0.74, 0.856, 0.14, 0.97, 0, 0.99, 0.862, 0.5, 0.234, 0.76)
df <- data.frame(name = name, percentage = percentage)

       name percentage
1     a      0.740
2     b      0.856
3     c      0.140
4     d      0.970
5     e      0.000
6     f      0.990
7     g      0.862
8     h      0.500
9     i      0.234
10    j      0.760

在y轴上应该是名称,在x轴上应该是百分比。对于每个名称,应绘制水平条。酒吧应分为两个部分:

  • 首先,长度等于百分比,根据百分比值着色:绿色,如果百分比&gt; 0.95,橙色,如果百分比> 0.85,否则为红色
  • 秒,长度为1 - 百分比,为灰色

我用barplot制作了类似规格的东西(但它很丑陋,并非所有的名字都可见而且没有第二部分):

barplot(df$percentage , main = "Percentage per letter", 
        horiz = TRUE,    names.arg = df$name, xlim = c(0,1),
        col = ifelse(df$percentage > 0.95, "green", 
        ifelse(df$percentage > .85,'orange','red')))

使用ggplot2,我设法实现了这个目标:

ggplot( data = df, aes( x = name, y = percentage)) +
  geom_bar(stat = "identity") + 
  coord_flip() + theme_minimal() 

有人可以给我一些提示吗?

编辑:

感谢@lukeA的帮助,我设法建立了非常好看的barplot。这是我的代码:

# Set colours (nice red, nice orange, nice green)
colours <- c("#D73027", "#FDAE61","#1A9850")

# Transform table:
df <- rbind(
  transform(df, type = 1, fill = cut(percentage, breaks = c(-Inf, 0.85, 0.95, Inf), right = TRUE, labels = colours)),
  transform(df, percentage = 1 - percentage, type = 2, fill = "#EEEEEE")
)

# Name as alphabetically ordered factor (to ensure, that names will be placed in 
# alphabetical order on y axis)
df <- within( df, name <- ordered(name, levels = rev(sort(unique(name)))))

ggplot(data = df, 
       aes( x = name, y = percentage, fill = fill)) +
  geom_bar(stat = "identity", position = "stack", width = 0.75) + 
  scale_fill_identity(guide = "none")  + 
  labs(x = NULL, y = NULL) + 
  scale_y_continuous(expand = c(0,0)) +
  scale_x_discrete(expand = c(0,0)) +
  coord_flip() +
  theme_classic() +
  theme(axis.ticks.y = element_blank(),
        axis.text.y = element_text(size = 11, colour = "black" ),
        axis.text.x = element_text(size = 11, colour = "black" ),
        axis.line = element_blank(),
        plot.margin = unit(c(10,10,10,10),"mm")
  )

--

1 个答案:

答案 0 :(得分:1)

你可以建立起来:

dat <- rbind(
  transform(df, fill = cut(percentage, breaks=c(-Inf,.85, .95, Inf), right = T, labels = c("red", "orange", "green"))),
  transform(df, percentage=1-percentage, fill="grey")
)
ggplot( data = dat, aes( x = name, y = percentage, fill = fill)) +
  geom_bar(stat = "identity", position="stack") + 
  scale_fill_identity(guide="none")+
  coord_flip() + theme_minimal() 
相关问题