使用多个类别的不同时间点的平均值的直方图

Histogram using the mean of different timepoints for multiple categories

我正在使用 R 分析我的硕士论文,我有一个年龄类别为 1 到 6 的数据,我有不同的时间点(1 到 7),我取了每个时间点的平均值。所以现在我有一个 6 x 8 table,我想制作一个直方图,说将年龄类别放在 x 轴上,将不同的时间点放在 y 轴上以进行比较。

数据:

Group.1 T0   T1   T2   T3   T4   T5   T6
1       0.52 0.64 0.65 0.54 0.87 0.65 0.73
2       0.87 0.54 0.65 0.60 0.87 0.65 0.87
3       0.97 0.48 0.65 0.60 0.87 0.36 0.88 
4       0.45 0.67 0.66 0.87 0.87 0.51 0.98
5       0.70 0.99 0.84 0.88 0.87 0.54 0.98
6       0.77 0.80 0.87 NaN  NaN  NaN  1.00

我使用了以下命令:

library(reshape2) 

new.df<-melt(data,id.vars="Group.1")
names(new.df)=c("Group.1","variable","value") 

library(ggplot2)

ggplot(data=new.df, aes(x=Group.1, y=value,fill=(variable)))+
    geom_histogram()

起初我收到一个错误代码 "error: Unknown parameters: binwidth, bins, pad" 所以我尝试指定,现在我收到错误代码 "Error: stat_bin() must not be used with a y aesthetic."

有人可以帮助我吗?我想要的是这样的:

Draw histograms per row over multiple columns in R

(第一个在上面有多种颜色)

谢谢。

萨斯

好的,首先您要寻找的是一个简单的 "grouped bar chart",而不是直方图。有关解释,请参阅 here。顺便说一句,这是一个使用玩具数据的简单示例:

首先我们重塑数据,假设您已经阅读了粘贴为 df <- read.table("clipboard", header = T) 的数据。请注意,我使用 tidyrgather() 函数来重塑数据,这类似于 reshape

# with dplyr & tidyr
library(dplyr)
library(tidyr)

df <- df %>% 
   gather(key, value, -Group.1)

# without dplyr
df <- reshape2::melt(df, id.var = "Group.1", variable.name = "key")

现在,只需正确设置 ggplot 中的组和颜色即可。

  ggplot(df, aes(x = Group.1, y = value)) + # 'Group.1' on the x-axis
  geom_bar(stat = "identity",               # stat = "identity", so we can use y values
           position = "dodge",              # this puts all the bars next to each other
           aes(group = key, fill = key)) +  # group and fill by time slot
  scale_fill_brewer(palette = "Set1") +     # this gives you nicer colors
  scale_x_continuous(breaks = 1:6)  

这给你:

也许这些可以帮助您入门:

#scatterplot
ggplot(data=new.df, aes(x=Group.1, y=value,colour=variable))+
       geom_point()

#barchart
ggplot(data=new.df, aes(x=Group.1, y=value,fill=variable))+
       geom_bar(stat="identity",position = "dodge")

#line + scatterplot
ggplot(data=new.df, aes(x=Group.1, y=value,colour=variable))+
       geom_point()+
       geom_line()