簡體   English   中英

如何在R中繪制帶有多個變量的直方圖?

[英]How to plot an histogram in R with several variables?

我必須在r中使用以下數據制作直方圖:

                     GDP: CONSTANT VALUES (2008=100)                                            

**sector**  **2003**    **2004**    **2005**    **2006**    **2007**
Agriculture   532918    543230        532043      562146    585812
Mining        1236807   1258769     1263937      1250930    1235517
Construction 1505948    1598346      1645017     1785796    1874591
Manufacturing 6836256   7098173     7302589      7731867    7844533
Wholesale      8635763  918174       966467       1037362   1070758

我知道制作非常簡單的數據直方圖(在一年中僅表示一個變量)的規則和步驟,如下所示:

age of members of group A in 2013
12 13 13 57 57 90 56 32 12 34 
16 23 23  23 14 67 89 90 35 92

問題是我非常困惑,因為前者是一個時間序列,其中包含多個變量,並且其數量在幾年內,而且我不知道如何制作一個直方圖來將所有數據一起繪制。

請你幫助我好嗎?

提前謝謝了。

我想你想要這樣的東西:

df <- read.table(text="sector  2003    2004    2005    2006    2007
Agriculture   532918    543230        532043      562146    585812
Mining        1236807   1258769     1263937      1250930    1235517
Construction 1505948    1598346      1645017     1785796    1874591
Manufacturing 6836256   7098173     7302589      7731867    7844533
Wholesale      8635763  918174       966467       1037362   1070758",h=T,strin=F)

library(ggplot2)
library(tidyr)

df2 <- gather(df,year,value,-sector)
ggplot(df2,aes(x=year,y=value,fill=sector)) + geom_bar(stat="sum")

在此處輸入圖片說明

由於行業不同,因此您可能希望查看按年份組織的行業內的數據。 一種方法如下。

rawData <-                                          
"sector  Year2003    Year2004    Year2005    Year2006    Year2007
Agriculture   532918    543230        532043      562146    585812
Mining        1236807   1258769     1263937      1250930    1235517
Construction 1505948    1598346      1645017     1785796    1874591
Manufacturing 6836256   7098173     7302589      7731867    7844533
Wholesale      8635763  918174       966467       1037362   1070758"

library(reshape2)

gdpData <- read.table(textConnection(rawData),header=TRUE,
                      sep="",stringsAsFactors=TRUE)

gdpMelt <- melt(gdpData,id="sector",
            measure.vars=c("Year2003","Year2004","Year2005","Year2006","Year2007"))

gdpMelt$year <- as.factor(substr(gdpMelt$variable,5,8))

library(ggplot2)
ggplot(gdpMelt, aes(sector, value, fill = year)) + 
     geom_bar(stat="identity", position = "dodge") + 
     scale_fill_brewer(palette = "Set1")

生成的圖表如下所示。 在此處輸入圖片說明

問候,

萊恩

暫無
暫無

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

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