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

R-stacked-grouped barplot with different fill in R

我有以下代码:

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')

此代码为我提供了以下情节。

不过,我想得到这样的条形图

k (10,8,5,2) 的每个值应该是一组条,条的每种颜色都是一个度量。此外,KK 值为 30 的条应该是实心的,KK 值为 10 的条应该被剥离。不知道说清楚了没有。在我的输出中出现了 K30 的值,但缺少 K10 合并与 K30 剥离。

您可以简单地将两个不同的图层添加到您的情节中,每个 KK 值一个。不幸的是,ggplot 不能很好地处理模式(或者根本不处理模式),参见这个 post: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')