tidyverse 是你的朋友!主要是ggplot2::geom_col。
您的代码可能如下所示:
library(tidyverse)
mytbl <- df %>%
mutate(racegender = paste(Race,Gender))
g <- ggplot(mytbl, aes(racegender)) + scale_fill_brewer(palette = "Spectral")
g + geom_col(aes(fill = Ethnicity, y = DiagAge)) +
labs(title="Your title",
subtitle="Your subtitle") +
theme(axis.text.x = element_text(angle=65, vjust=0.6))
这里我使用diamonds 数据集上的这段代码来说明你的情况。
library(tidyverse)
通过mutate 创建一个cutcolor 变量。在我的示例中,为了简洁起见,我 filter 指定了某些值(很可能对您来说不是必需的或有效的)。
mytbl <- diamonds %>%
mutate(cutcolor = paste(cut,color)) %>%
filter(color %in% c("D", "E", "F"),
cut %in% c("Fair", "Good", "Very Good")) # to limit the number of columns
图表将使用mytbl,并在横轴上使用cutcolor:
g <- ggplot(mytbl, aes(cutcolor)) + scale_fill_brewer(palette = "Spectral")
主要的ggplot 函数是geom_col。 fill 堆叠它们,垂直轴是 price(在您的情况下为 DiagAge)。 theme 部分有助于调整水平标签文本的角度。
g + geom_col(aes(fill = clarity, y = price)) +
labs(title="Bar Graph with Stacked Types",
subtitle="Price Across Diamond Cut and Color") +
theme(axis.text.x = element_text(angle=65, vjust=0.6))angle=65, vjust=0.6))
结果: