2016-11-26 65 views
0

我試圖與x軸的年齡和Y軸爲0或1(true或false)直方圖/ ggplot x和y與真實的假

person = c(1:50) 
age = sample(1:5,50,replace=T) 
drunk = sample(0:1,50,replace=T) 
df = data.frame(person,age,drunk) 

#plots that I tried: 
ggplot(df, aes(x = age, y = drunk)) + 
    geom_bar(stat="identity") 

hist(df$age) 

barplot(df$drunk, names.arg=df$age) 

這些圖是一個直方圖不爲我工作。我想要得到的是:X軸應該看起來像50個號碼從1-5和Y軸應該是0或1(TRUE或FALSE)

df$drunk <- as.character(df$drunk) 
df$drunk[df$drunk == "0"] <- "False" 
df$drunk[df$drunk == "1"] <- "True" 

我嘗試使用上面的代碼做一個陰謀,但它不工作。例如

http://i.imgur.com/c2DoEha.png。每個人都有一個隨機年齡的情節,並顯示其如果他/喝醉(0 - 1或真/假)

+0

這部分我不明白: 「X軸應該看起來像50號,從1-5」。你可以手工繪製圖片並上傳嗎? –

+0

@KotaMori我添加了一個圖像和描述 – Aanna

回答

2

您需要:

  1. 改變你aesperson
  2. 的X,aes
  3. 添加factor(drunk)你Y添加scale_y_discrete標記真假代替1和0
  4. y軸添加scale_x_discretelabel使用輔助功能,並且設置爲person變量的範圍的限制來改變person蜱標籤到對應agedf

    ggplot(df, aes(x = person, y = factor(drunk))) + 
        geom_bar(stat="identity") + 
        labs(x = "Age", y = "Drunk") + 
        scale_y_discrete(labels = c("FALSE","TRUE")) + 
        scale_x_discrete(limits = seq(min(df$person), max(df$person)), labels = function(x) df[df$person == x,]$age) 
    

enter image description here

+0

嗨,謝謝!人們應該如何處理數百行的人物/年齡? – Aanna

+0

這應該適用於'df'中的任意行數,只要它們是唯一的。 –

0

這是否對你的工作

ggplot(df,aes(x=person,y=age,fill=factor(drunk))) + geom_bar(stat='identity') 
+0

它確實有效,但這不是我要找的。年齡應該是x軸,醉(0或1)應該是y軸。我嘗試編輯代碼到ggplot(df,aes(x = age,y = drunk,fill = drunk))+ geom_bar(stat ='identity'),但這不起作用 – Aanna

相關問題