如何更改包含并排条形图和线图(2 个不同数据集)的图形的颜色方案

问题描述 投票:0回答:1

我正在尝试使用 2 个数据集创建一个包含并排条形图和线图的图形。我的问题与另一篇文章略有不同,我创建了图形,但两个类别的并排条形图都是灰色的,条形的轮廓是我需要填写的颜色。现在,我已经创建了mycolors 变量,我什至不确定是否需要......我在这个图中还有其他几段代码,我在这里找到的,所以不确定它们是否会相互影响(即系数创建和使用所述值)创建一个辅助轴,我理解这可能不是最佳实践,但这就是他们想要的,所以这就是他们得到的..)

其他一些信息:数据集 p 是一个长数据集,包含一个“计数”变量,该变量具有两个级别(类型 1 和类型 2)以及每个计数类型按年份的“值”。条形图应按类型 1 和类型 2 进行分割。数据集 q 是按年份进行的一个度量并创建线条。我在下面提供了代码和示例数据。另外,我尝试使用 fill=count 与 color=count 但 R 给了我以下错误

'由 FUN() 中的错误引起: !未找到对象“计数”

注意:我提供了该图的输出。下面的代码被修改为示例,因此如果直接复制/粘贴,则不会输出所需的数字。我将数据集 p 转换为长数据集,以便将其用作并排图。

数据集p

Year<-c(2012,2013,2014,2015,2016)
Count<-c("type1","type2")
Value<-c(1,5,4,9,7,11,19,16,2,14,1,4)

数据集q

Year<-c(2012,2013,2014,2015,2016)
proportion<-c(0.5,0.2,0.4,0.6,0.8)

mycolors=c("darkseagreen", "lightsteelblue","darkgrey")

ylim.prim <- c(0, 20)   
ylim.sec <- c(0, 1)
b <- diff(ylim.prim)/diff(ylim.sec)
a <- ylim.prim[1] - b*ylim.sec[1]


example <- ggplot(data=p, aes(x=year, y=value*10000, colour=count)) +  
geom_bar(stat="identity", width=.5, position = "dodge")+
geom_line(data=q, aes(y=a+proportion*b), color="darkseagreen",linewidth=1.2)+
scale_y_continuous("Counts, per 10,000 events", sec.axis = sec_axis(~ (. - a)/b, name = "Percent Success")) +
scale_x_continuous("Year", breaks=seq(2012,2022, by=1)) +
ggtitle("Example figure comparing counts and success rate")+
theme_bw()+
scale_fill_manual(values=mycolors)+
scale_color_manual(values=mycolors, labels=c("Proportion", "Type1","Type2"))+
theme(legend.position="bottom")
example

输出 Attempted figure

r ggplot2 visualization
1个回答
0
投票

您正在寻找

fill
而不是
color
。但是,哦不!您已经使用过
color
。所以你可以为每层
aes()
geom_bar
指定一组
geom_line

example <- ggplot() +  
  geom_bar(stat="identity", width=.5, position = "dodge", data=p, aes(x=year, y=value*10000, fill=count))+
  geom_line(data=q, aes(x=year, y=a+proportion*b), color="darkseagreen",linewidth=1.2) +
  scale_y_continuous("Counts, per 10,000 events", sec.axis = sec_axis(~ (. - a)/b, name = "Percent Success")) +
  scale_x_continuous("Year", breaks=seq(2012,2022, by=1)) +
  ggtitle("Example figure comparing counts and success rate")+
  theme_bw()+
  scale_fill_manual(values=mycolors)+
  scale_color_manual(values=mycolors, labels=c("Proportion", "Type1","Type2"))+
  theme(legend.position="bottom")
example
© www.soinside.com 2019 - 2024. All rights reserved.