r - 在 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 轴上的所有变量和直方图中的数量,但我得到了一个“意外错误”
解决方案
如果我对您的理解正确,您所要求的只是将这五个值绘制在带有对数 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。
推荐阅读
- python - 使用 BeautifulSoup 查找特定的 span 元素
- python - 如何在 Django 模板中获得反向引用?
- r - R根据列数据创建箱线图
- elasticsearch - Kibana / Elastic - 不能使用数组字段
- loops - “ValueError:要解压的值太多(预期为 2)”不应在此处发生
- javascript - JavaScript - 通过 Flask 获取列表中的第 i 个元素
- reactjs - 在 TailwindCss 中动态构建类名
- c# - .Net Core Web API 分页列表 - 源“IQueryable”的提供程序未实现“IAsyncQueryProvider”
- flutter - Flutter Fitness 读取步数数据的插件
- c# - 更改源文件的位置