如何制作 x 轴上有两组的分组条形图

How to make a grouped barchart with two groups on x-axis

我有一个看起来像这样的数据

Name, Clusters, incorrectly_classified
PCA, 2, 34.37
PCA, 6, 60.80
ICA2, 2, 37.89
ICA6, 2, 33.20
ICA2, 6, 69.66
ICA6, 6, 60.54
RP2, 2, 32.94
RP4, 2, 33.59
RP6, 2, 31.25
RP2, 6, 68.75
RP4, 6, 61.58
RP6, 6, 56.77

我想为上面的数据创建一个类似于我画的这个图的条形图

x 轴将有两个数字 2 或 6。Y 轴将有 incorrectly_classified,并且将为每个 26 绘制 Name。每个组(2 或 6)的每个名称将在两组中一致地着色。

这可以用条形图实现吗?如果不使用条形图,那么绘制这些数据的好方法是什么

这可以用 barplot 来完成。

一个例子:

counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
  xlab="Number of Gears", col=c("darkblue","red"),
    legend = rownames(counts), beside=TRUE)

编辑

我也会用我的答案来演示 barplot 选项(尽管 ggplot 更酷:-)):

如果 df 是你的数据框:

dfwide<-reshape(df,timevar="Clusters",v.names="incorrectly_classified",idvar="Name",direction="wide")
rownames(dfwide) <- dfwide$Name
dfwide$Name<-NULL
names(dfwide)[names(dfwide)=="incorrectly_classified.2"] <- "2"
names(dfwide)[names(dfwide)=="incorrectly_classified.6"] <- "6"

dfwide<-as.matrix(dfwide)

barplot(dfwide, main="Your Graph",
        xlab="Clusters",ylab="incorrectly_classified",col=c("darkblue","red","orange","green","purple","grey"),
        legend = rownames(dfwide), beside=TRUE,args.legend = list(x = "topleft", bty = "n", inset=c(0.15, -0.15)))

我认为以下是您所追求的。

ggplot(data = mydf, aes(x = factor(Clusters), y = incorrectly_classified, fill = Name)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "Clusters", y = "Incorrectly classified")