【问题标题】:How to make a grouped barchart with two groups on x-axis如何在 x 轴上制作具有两组的分组条形图
【发布时间】:2015-06-09 02:49:19
【问题描述】:

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

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_classifiedName 将为每个 26 绘制。每个组(2 或 6)的每个名称将在两组中一致地着色。

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

【问题讨论】:

  • 这可以通过 ggplot 和 geom_bar 实现。我可以发布解决方案,但我需要更多信息。 y 轴将是“incorrectly_classified”值,但您希望如何组合这些值?例如倒数第三行和最后一行具有相同的名称和相同的簇,那么您希望如何组合这两个值(65.49 和 56.64)?和?意思是?
  • @jwilley44 您可以忽略具有相同名称和相同集群的那些。我已编辑问题并删除了这些行。

标签: r plot ggplot2


【解决方案1】:

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

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

【讨论】:

  • 太棒了,看起来很棒!此外,您的个人资料中还有很棒的飞行地图!
  • @birdy 感谢您的评论。我很高兴这对您有所帮助。也感谢您对飞行地图的评论!
  • 我用带有 R 的 barplot() 在其他答案中得出了我的答案,但我同意 ggplot 也是更好的选择
  • @jebsel 如果你可以使用 base R 来制作图形,我认为这是一个加分项。
【解决方案2】:

这可以通过条形图来完成。

一个例子:

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

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2018-11-25
    相关资源
    最近更新 更多