2016-07-25 75 views
0

我假设我在问一个非常简单的问题,但是我无法自己解决它。我如何在下图中的x轴上创建年龄段。例如,10-20,20-30,40-50等在ggplot之内?在geom_bar中结合X轴上的行

enter image description here

我知道我可以创建一个新的数据帧,但我宁愿让我的工作简单而内ggplot做到这一点。这是我正在使用的代码:

figure1 <- ggplot(newdata, aes(x = factor(Leeftijd),)) + geom_bar() + xlab("Age") + 
ylab("Loneliness (count)") + ggtitle("Overview of the distrubtion of lonely people") 

figure1 

谢谢!

+2

应该使用'geom_histogram()'与给予'箱='说法箱的您的首选号码。 – mtoto

+0

试过了,这是我使用的代码:'ggplot(newdata,aes(x = factor(Leeftijd))+ geom_histogram(bins = 20)+ xlab(“Age”)+ ylab(“Loneliness(count) “)+ ggtitle(”孤独的人的分布概述“)。 但是,我收到以下错误消息:'错误:StatBin需要一个连续的x变量x变量是离散的。也许你想stat =“count”?'我使用了一个连续变量,所以我不知道如何处理这个错误。你有任何线索@mtoto? – Keizer

+0

取出'factor'调用,所以'geom_histogram'(嗯,'stat_bin',真的)可以告诉变量的顺序是什么,因此如何对它进行处理。此外,为了使问题可重现,您需要发布足够的数据(最好是'dput(newdata)'的结果)来模拟问题。 – alistaire

回答

0

首先你没问的问题,但我想回答。我发现在进入ggplot之前通过dplyr和tidyr提供数据帧要好得多。

它使得代码更加可读,并且让你的头脑变得更加简单。

其次,你想要做什么:

library(ggplot2) 
library(tidyr) 
library(dplyr) 


## I created some dummy data here, you want to use your own, obviously 
newdata <- data.frame(as.numeric(round(rnorm(1000,50,10)))) 
colnames(newdata) <- c("Leeftijd") 


figure1 <- ggplot(newdata, aes(x = factor(Leeftijd),)) + geom_bar() + xlab("Age") + 
    ylab("Loneliness (count)") + ggtitle("Overview of the distrubtion of lonely people") 

figure1 


## This does what you want, change the binwidth to whatever you're interested in. 
newdata %>% 
    ggplot() + 
    aes(x=Leeftijd) + 
    geom_histogram(binwidth=10, stat="bin") + 
    labs(x="Age", 
     y="Loneliness (count)", 
     title="Overview of the distribution of lonely people") 
+1

加载'dplyr'或'tidyr'在这里完全没有意义。 – mtoto

+0

感谢您的意见。我总是加载它们 - 我需要dplyr管道进入ggplot –