簡體   English   中英

使用ggplot2的barplot

[英]barplot using ggplot2

我有一個這樣的數據集:

cars    trucks  suvs
1          2    4
3          5    4
6          4    6
4          5    6
9          12   16

我正在嘗試為此數據繪制條形圖。 目前,我可以使用barplot來做到這barplot

barplot(as.matrix(autos_data), main="Autos", 
         ylab= "Total",beside=TRUE, col=rainbow(5))

生成此圖:

條形圖

所以我的問題是:我可以使用ggplot2繪制這樣的圖形嗎? 具體來說-如何使用構面或其他選項按星期幾划分圖表? 如果是,我該怎么做? 此外,如何使用構面來產生不同的布局?

這已經被問過很多次了。 答案是您必須在geom_bar使用stat="identity"來告訴ggplot不要匯總您的數據。

dat <- read.table(text="
cars    trucks  suvs
1   2   4
3   5   4
6   4   6
4   5   6
9   12  16", header=TRUE, as.is=TRUE)
dat$day <- factor(c("Mo", "Tu", "We", "Th", "Fr"), 
             levels=c("Mo", "Tu", "We", "Th", "Fr"))

library(reshape2)
library(ggplot2)

mdat <- melt(dat, id.vars="day")
head(mdat)
ggplot(mdat, aes(variable, value, fill=day)) + 
  geom_bar(stat="identity", position="dodge")

在此處輸入圖片說明

這是和tidyr

這里最大的問題是您需要將數據轉換為整齊的格式。 我強烈建議閱讀R for Data Science( http://r4ds.had.co.nz/ ),以使您入門並使用整潔的數據和ggplot。

通常,一個好的經驗法則是,如果您必須輸入同一geom的多個實例,則可能存在一種數據格式的解決方案,該解決方案使您可以將所有內容放入頂級ggplot()中的aes()函數中ggplot() 在這種情況下,您需要使用gather()適當地安排數據。

library(tidyverse)

# I had some trouble recreating your data, so I just did it myself here
data <- tibble(type = letters[1:9], 
               repeat_1 = abs(rnorm(9)), repeat_2  
               =abs(rnorm(9)), 
               repeat_3 = abs(rnorm(9)))

data_gathered <- data %>%
  gather(repeat_number, value, 2:4)

ggplot(data_gathered, aes(x = type, y = value, fill = repeat_number)) +
geom_col(position = "dodge")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM