首页 > 解决方案 > 在 x 轴上绘制 1 个具有多个变量的直方图

问题描述

我有多个变量,我想在 1 个图表中可视化。它是多个类别的数字总和。数据集是 total_sales

Sum_Clothes Sum_Shoes Sum_Bags  Sum_Belts  Sum_Glasses
101456         56709    152908    40670      97654

我尝试使用 ggplot 来创建这个

ggplot(total_sales, aes(x=c("Sum_Clothes", "Sum_Shoes", "Sum_Bags", "Sum_Belts", "Sum_Glasses"))) + 
geom_histogram(bin=10) + scale_x_log10()

我期望一个图显示 x 轴上的所有变量和直方图中的数量,但我得到了一个“意外错误”

标签: rggplot2histogram

解决方案


如果我对您的理解正确,您所要求的只是将这五个值绘制在带有对数 y 轴的条形图中。

首先,您需要转置数据框。

total_sales <- t(total_sales)

#If you're not working with a data.frame, instead run this and skip to the plot-section:

total_sales <- data.frame(sums = names(total_sales), total_sales)

接下来重命名你的列名

colnames(total_sales) <- c("sums", "sales")

最后,使用标准 ggplot2-functions 绘图

ggplot(total_sales, aes(x=sums, y=sales), fill=sums) + 
  geom_histogram(stat = 'identity') + scale_y_continuous(trans="log10")

编辑:添加了一个填充参数,因此每个总和的颜色应该不同。我怀疑由于总和的相似性,您收到了一个深灰色的情节。

bin 参数表示您希望条形图有多少条。在给定的数据中,您需要 5 个 bin 来正确表示数据(每个总和 1 个 bin)。由于有 5 个不同的总和,ggplot 会自动将 bin 的数量设置为 5。


推荐阅读