簡體   English   中英

如何在R中使用ggplot繪制多個構面直方圖?

[英]How to plot multiple facets histogram with ggplot in r?

我有一個像這樣的數據框

 Elem. Category. SEZa SEZb SEZc

  A.     ONE.     1.   3.   4
  B.     TWO.     4.   5.   6

我想用ggplot在三個不同的方面(SEZa,SEZb,SEZc)中繪制三個直方圖,其中x值是類別值(一。e兩個),y值是SEZa,SEZb,SEZc列中的數字。

像這樣的東西:

在此處輸入圖片說明

我能怎么做? 謝謝你的建議!

假設df是您的data.frame,我首先將其從寬格式轉換為長格式:

new_df <- reshape2::melt(df, id.vars = c("Elem", "Category"))

然后使用geom_col()而不是geom_col()進行geom_histogram()因為您似乎已經預先計算了y值,並且不需要ggplot為您計算這些值。

ggplot(new_df, aes(x = Category, y = value, fill = Elem)) +
  geom_col() +
  facet_grid(variable ~ .)

我認為您正在尋找的是這樣的:

library(ggplot2)
library(reshape2)

df <- data.frame(Category = c("One", "Two"),
                 SEZa = c(1, 4),
                 SEZb = c(3, 5),
                 SEZc = c(4, 6))

df <- melt(df)

ggplot(df, aes(x = Category, y = value)) +
  geom_col(aes(fill = variable)) + 
  facet_grid(variable ~ .)

我的靈感是:

http://felixfan.github.io/stacking-plots-same-x/

暫無
暫無

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

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