[英]turning stacked bar graph from R into ggplot2
這類問題通常是數據重組問題。 請參閱將 data.frame 從寬格式重塑為長格式。
以下代碼使用內置數據集iris
,具有 4 個數字列,plot 是一個條形圖,其中數據值在重塑數據后被切割成多個級別。
我選擇了截止點0.2
和0.7
,但(0, 1)
中的任何其他數字都可以。 截止向量是brks
和級別名稱labls
。
library(tidyverse)
data(iris)
brks <- c(0, 0.2, 0.7, 1)
labls <- c('Small', 'Medium', 'Large')
iris[-5] %>%
pivot_longer(
cols = everything(),
names_to = 'Category',
values_to = 'Value'
) %>%
group_by(Category) %>%
mutate(Value = (Value - min(Value))/diff(range(Value)),
Level = cut(Value, breaks = brks, labels = labls,
include.lowest = TRUE, ordered_result = TRUE)) %>%
ggplot(aes(Category, fill = Level)) +
geom_bar(stat = 'count', position = position_fill()) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.