2017-11-18 101 views
0

直方图绘制在x轴上多个标签,我在下面的格式的数据审美错误,而使用ggplot

occupation,how_many_happy, how_many_not_happy 
Teacher, 50, 30 

我试图通过对每个x轴同时使用how_many_happyhow_many_not_happy绘制直方图职业separatly使用ggplot如下

ggplot(Occupations_vs_parties, 
     aes(x = c(Occupations_vs_parties$How_many_happy, 
       Occupations_vs_parties$How_many_not_happy))) + 
     facet_wrap(~Occupation, nrow = 4) 

但是我收到如下错误

Error: Aesthetics must be either length 1 or the same as the data (17): x 

你可以请我帮助我的前进方向。请让我知道如果任何输入需要

感谢, 苏里亚

+0

您的代码中存在基本的'ggplot'语法错误,我不想编辑。请参阅下面的示例解决方案。 –

回答

1

有在你的代码相当多的错误。 (1)converting data from wide to long format,和(2)通用ggplot语法,特别是使用geom_histogramgeom_bar(例如,你实际上没有指定如何你想绘制你的数据)。

对于您给出的示例数据,在包面occupation中也没有意义。因此,您的示例数据可能不是一个具有代表性的最小示例

这是一个基于您的样本数据的简单的barplot。

# Sample data 
df <- read.csv(text = 
    "occupation,how_many_happy,how_many_not_happy 
    Teacher,50,30", sep = ","); 

# Convert wide to long dataframe 
library(reshape2); 
df.long <- melt(df); 

# (gg)plot 
require(ggplot2); 
ggplot(df.long, aes(x = variable, y = value)) + geom_bar(stat = "identity"), 

enter image description here

如果你有不同的occupation水平,你可以添加... + facet_wrap(~ occuptation)ggplot命令。