首页 > 解决方案 > 尝试对数据进行分组并绘制 ggplot 直方图时出现问题

问题描述

我有一个 csv 文件,其中包含这三列数据条目:

before           after             Style             
14                 20              group
2                  0               alone
17                 17              alone
4                  2               group
6                  3               group

我设法绘制了一个比较前后值的 ggplot 直方图。

library(ggplot2)
library(reshape2)
responses = read.csv("dataframe.csv")

responses$exercise_style <- as.factor(responses$exercise_style)
responses$Exercise_before = as.numeric(as.character(responses$Exercise_before))
responses$Exercise_after = as.numeric(as.character(responses$Exercise_after))

before = responses$Exercise_before
after = responses$Exercise_after

Style = responses$exercise_style

frame1 = data.frame(before,after,hours)
frame2 = melt(frame1,id.vars = 'hours')

plotting = ggplot(frame2,aes(x = hours, y = value, fill = variable))

Bars = geom_bar(stat="identity",position="dodge")

plotting + Bars

在此处输入图像描述 但问题是它只比较“前后”值,有没有办法也考虑“风格”因素并将数据分组?

标签: rggplot2reshape2

解决方案


您正在尝试表示 3 维数据。我能想到的唯一方法是,因为您只有 2 种样式,您可以为不同的样式使用不同的颜色组。例如,单独可以使用蓝色和青色,可以使用红色和黄色。只是一个意见


推荐阅读