簡體   English   中英

如何使用來自 dataframe 的數據在 R 中制作堆疊條 plot?

[英]How to make a stacked bar plot in R with the data from a dataframe?

我有一個如下所示的表:

家庭 最大限度 意思是
OG0000000 1336 348.23423423423424
OG0000001 152 66.31531531531532
OG0000002 104 33.85585585585586
OG0000003 133 32.990990990990994
OG0000004 118 31.135135135135137
OG0000005 79 30.83783783783784
OG0000006 123 30.153153153153152
OG0000007 131 29.81081081081081
OG0000008 129 29.684684684684683
OG0000009 93 29.405405405405407
OG0000011 169 28.35135135135135
OG0000012 73 27.56756756756757
OG0000013 113 27.504504504504503
OG0000014 87 24.72972972972973
OG0000015 106 24.675675675675677
OG0000017 131 23.306306306306308
OG0000018 80 22.81081081081081
OG0000020 234 21.324324324324323
OG0000024 89 20.89189189189189

我想制作一個條形 plot ,其中每個條形將第一列('family')中的數據作為 label 並將每個條形的第二列和第三列中的數據堆疊起來。 假設第二列的數據點構成了條形圖中顯示的主要數據,第三列的數據覆蓋在它上面。

我正在嘗試在 ggplot 中執行此操作。

我嘗試了以下方法(取自這篇文章):

df_long <- df2 %>% gather(family,counts, 2:3) # here df is the above table as a dataframe
ggplot(df_long, aes(x = family, y = counts, fill = family)) + geom_col(position = position_stack())

這在以下設計中給出了 output,這真的不是我想要的。

此代碼生成的圖像

不確定鏈接帖子中的代碼是否已過時或者我做錯了什么。

我在這里(例如)看到了一些隨機網頁,並且那里顯示了類似barplot(Values, main = "total revenue", names.arg = months, xlab = "month", ylab = "revenue", col = colors)的語法制作條形圖,但這里的values object 需要是一個向量(我不確定如何將兩組數據傳遞給它。)

在谷歌上搜索,似乎堆積的條形圖有點難以追蹤。 不幸的是,我grammar of graphics不是最熟悉的,有人有什么指點嗎?

如果您想將每個家庭的最大值和平均值疊加在一起,那么您可以執行以下操作:

library(tidyverse)

df2 %>%
  pivot_longer(-family) %>%
  ggplot(aes(x = family, y = value, fill = name)) +
  geom_col(position = position_stack()) +
  theme(axis.text.x = element_text(angle = 90))

Output

在此處輸入圖像描述

另一種選擇(而不是混合統計數據)是使用facet_wrap ,這樣你的意思是在一個圖中,在另一個圖中是 max:

df2 %>%
  pivot_longer(-family) %>%
  ggplot(aes(x = family, y = value)) +
  geom_col(position = position_stack()) +
  scale_y_continuous(breaks = seq(0, 1400, 200),
                     limits = c(0, 1400)) +
  facet_wrap( ~ name, scales = "free_y") +
  theme(axis.text.x = element_text(angle = 90))

在此處輸入圖像描述

暫無
暫無

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

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