带双线图的堆叠图

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

`

#packages required
library("readxl")
library("ggplot2")
library("dplyr")
library("reshape")  
library("scales")

# Adding a column with the sum of x and y

#>    x chromosome plasmid gc(%)  cds
#> 1  1998  1        0     50.8   4298 
#> 2  2001  0        1     50.4   4132
#> 3  2002  1        1     51.2   3954
#> 4  2006  2        2     50.2   4200

years_data <- read_excel("D:/menuscript/forgraph.xlsx", sheet = "data")
years_data <- as.data.frame(years_data)
years_data_long <- melt(years_data, id.vars = "Year")
years_data_long <- years_data_long[years_data_long$variable %in% c("chromosome", "plasmid","gc","cds"), ]
ggplot(years_data_long, aes(x = Year, y = value, fill = variable)) +`
  geom_bar(stat = "identity", position = "stack") +
  labs(x = "Year", y = "Count", fill = "Type") +
  ggtitle("Counts by Year") +
  scale_x_continuous(breaks = years_data$Year)+
  theme(axis.text.x = element_text(angle = 45, vjust = 0, hjust=0))

################################################## ##` 我得到了这个,但我需要 gc 和 cds 作为线图,以及堆叠的染色体和质粒

就像这张图片需要但双线。一行代表 gc 另一行代表 cd

r
1个回答
0
投票

如果您可以在问题中包含您的数据或虚假数据,以便我们重现您的结果,将会很有帮助。

要向条形图添加线条,您应该将

aes(x = Year)
保留在
ggplot()
中,但删除
y
参数。然后,在每个
aes(y)
步骤中指定
geom_**

我已经调整了下面的代码以适应这一点。现在每个

aes(y =)
参数中都有一个
geom

years_data <- read_excel("D:/menuscript/forgraph.xlsx", sheet = "data")
years_data <- as.data.frame(years_data)
years_data_long <- melt(years_data, id.vars = "Year")
years_data_long <- years_data_long[years_data_long$variable %in% c("chromosome", "plasmid","gc","cds"), ]
ggplot(years_data_long, aes(x = Year) +`
  geom_bar(aes(y = value, fill = variable), stat = "identity", position = "stack") +
 geom_line(aes(y = cds)) +
 geom_line(aes(y = gc)) + 
  labs(x = "Year", y = "Count", fill = "Type") +
  ggtitle("Counts by Year") +
  scale_x_continuous(breaks = years_data$Year)+
  theme(axis.text.x = element_text(angle = 45, vjust = 0, hjust=0))

© www.soinside.com 2019 - 2024. All rights reserved.