我想將“收入”的類別從 1,2,3,4,5 重命名為圖中收入的實際值。我試過這段代碼,但它不起作用。有人可以解釋我為什么嗎?
ggplot(data=subset(trips_renamed,income!="99"))
geom_bar(mapping = aes(x = income,fill="income"))
scale_x_discrete(labels=c("<=4000","4001-8000","8001-12000","12001-
16000",">16000",position="bottom"))
labs(y= "Total number of trips", x="Income Classes")
theme(legend.position = "none")
uj5u.com熱心網友回復:
如果您提供了一個最小的可重現示例,則查找和測驗答案會容易得多。但是,下面顯示了如何更改與您的問題類似的圖的比例。由于x的值是數值,我們需要使用(有點違反直覺)scale_x_continuous來更改標簽上飛
library(ggplot2)
ggplot(data=mtcars)
geom_bar(aes(x = gear))
scale_x_continuous(breaks = 3:5, labels=c("<4", "4-4.9",">4"))
回傳:

uj5u.com熱心網友回復:
看來您的問題與trips_renamed$income成為班級"integer"或"numeric". 因此,scale_x_discrete()應替換為scale_x_continuous(). 您可以使用scale_x_continuous()或轉換為離散值(因子),然后使用scale_x_discrete(). 以下是使用以下虛擬資料集的兩個示例。
set.seed(8675309)
df <- data.frame(income=sample(1:5, 1000, replace=T))
選項 1:重新標記您的連續軸
如果class(trips_renamed$income)是"numeric"或"integer",那么您將需要使用scale_x_continuous(). 重新標記要求您同時指定breaks=和labels=引數,并且它們的長度必須相同。這應該有效:
ggplot(df, aes(x=income)) geom_bar()
scale_x_continuous(breaks=1:5, labels=c("<=4000","4001-8000","8001-12000","12001-
16000",">16000"),position="bottom")

選項 2:轉換為因子并使用離散比例
另一種選擇是先轉換為因子,然后使用scale_x_discrete(). 在這里,您不需要breaks=引數(使用因子的級別):
df$income <- factor(df$income)
ggplot(df, aes(x=income)) geom_bar()
scale_x_discrete(labels=c("<=4000","4001-8000","8001-12000","12001-
16000",">16000"),position="bottom")
你得到與上面相同的情節。
選項 2a:一起分解和定義標簽
如果你想變得非常狡猾,你可以在定義因子的同時定義標簽,它們將用于軸標簽而不是級別的名稱:
df2 <- df
df2$income <- factor(df2$income, labels=c("<=4000","4001-8000","8001-12000","12001-
16000",">16000"))
ggplot(df2, aes(x=income)) geom_bar()
這一起應該讓您很好地了解ggplot2在選擇如何標記軸時的作業原理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315889.html
