R-堆叠分组的条形图,具有不同的R填充

时间:2016-06-28 08:25:22

标签: r ggplot2 bar-chart stacked

我有以下代码:

library(ggplot2)

K  <- data.frame(KK=c("30", "30", "30", "30","10", "10", "10", "10"),k=c("10", "8", "5", "2","10", "8", "5", "2"), 
               Precision=c(85.2,87.5,100,100,82.5,83.3,85.2,94.4),     
               Recall=c(73.3,80,100,100,51.4,54.8,61.1,87.9) , 
               Fscore=c(70.8,79.4,100,100,49.1,54.2,62.7,90.3),
               Accuracy=c(82.2,86.7,100,100,63.3,66.7,73.3,93.3)) 
  df2 <- reshape2::melt(K, 1:2)

   ggplot(df2, 
   aes(k, value, fill = variable)) + 
  geom_bar(stat = 'identity', position = 'dodge') +
 theme(legend.position = 'top')

此代码给出了以下图表。 enter image description here

但是,我想得到像这样的条形图

enter image description here

k(10,8,5,2)的每个值应该是一组条形,并且条形的每种颜色都是公制。另外,KK值30的棒应该是实心的并且KK为10剥离。我不知道是否清楚。在我的输出中显示K30的值,但缺少K10合并K30剥离。

1 个答案:

答案 0 :(得分:4)

您可以简单地为每个KK值添加两个不同的图层。不幸的是,ggplot无法很好地处理模式(或者根本没有),请参阅此帖子:How to add texture to fill colors in ggplot2?

为每个KK值添加不同图层的代码是:

ggplot() + 
  geom_bar(data=df2[which(df2$KK==10),], aes(k, value, fill = variable),stat = 'identity',position="dodge") +
  geom_bar(data=df2[which(df2$KK==30),], aes(k, value, fill = variable),stat = 'identity',position="dodge",alpha=0.5) +
  theme(legend.position = 'top')

enter image description here