提问人:Jin.w.Kim 提问时间:11/17/2023 最后编辑:M--Jin.w.Kim 更新时间:11/17/2023 访问量:44
如何创建条形图以直观地表示两个变量,同时保持 x 轴变量的相同颜色?
How to create a bar graph to visually represent two variables, while keeping the same color for the x-axis variable?
问:
例如,下面是一个数据。
Genotype=c("A","A","B","B","C","C","A","A","B","B","C","C")
Season=c("2022","2023","2022","2023","2022","2023","2022","2023","2022","2023","2022","2023")
Type=c("I","I","I","I","I","I","II","II","II","II","II","II")
Yield=c(100,120,110,80,60,90,100,100,170,80,30,90)
dataA= data.frame(Genotype, Season, Type, Yield)
我创建了一个条形图
ggplot(data=dataA, aes(x=Genotype, y=Yield, fill=Genotype, group1=Season, color=Season))+
geom_bar(stat="identity",position="dodge", width= 0.7, size=1) +
scale_fill_manual(values=c("darkred","blue","grey")) +
scale_color_manual(values=c("black","orange")) +
labs(x="Genotype", y="Yield") +
theme_classic(base_size=18, base_family="serif") +
theme(legend.position="right",
legend.title=element_blank(),
legend.key=element_rect(color="white", fill="white"),
legend.text=element_text(family="serif", face="plain",
size=15, color="black"),
legend.background= element_rect(fill="white"),
axis.line = element_line(linewidth = 0.5, colour="black"))+
windows(width=7, height=5)
但是,我的意图是只展示本赛季的传奇。在每个基因型中,我的目标是在区分两个条形时保持一致的颜色,可能使用线条、破折号或其他视觉区别。例如,如下图所示,或者用其他方式区分两个季节之间的两个条形。
你能告诉我怎么做吗?
答:
3赞
Allan Cameron
11/17/2023
#1
使用 ,您可以执行以下操作:ggpattern
library(tidyverse)
library(ggpattern)
dataA %>%
group_by(Season, Genotype) %>%
summarise(Yield = sum(Yield), .groups = "drop") %>%
ggplot(aes(Genotype, Yield, fill = Genotype, pattern = Season,
pattern_type = Season)) +
geom_col_pattern(position = "dodge", pattern_fill = "black", color = "black",
pattern_angle = 45, pattern_spacing = 0.02,
pattern_color = "black") +
scale_pattern_type_manual(NULL, values = c("none", "stripe")) +
scale_pattern_manual(NULL, values = c("none", "stripe")) +
scale_fill_manual(values = c("darkred", "blue", "grey"), guide = "none") +
theme_classic(base_size=18, base_family="serif") +
theme(legend.key = element_rect(color = "white", fill = "white"),
legend.text = element_text(color = "black"),
axis.line = element_line(linewidth = 0.5, colour = "black"))
请注意,目前尚不清楚要如何处理该变量。据推测,由于初始图中没有引用此类型,因此您希望将这两种类型堆叠在一起,我在这里通过在绘图之前对它们求和来完成。Type
评论
0赞
Jin.w.Kim
11/17/2023
非常感谢!!这正是我想要的。谢谢!!!
评论