同一图中的并排和折线图

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

我想在R中创建一个包含并排条形图和折线图的图,如下所示:

“

我尝试过:

Total <- c(584,605,664,711,759,795,863,954,1008,1061,1117,1150)
Infected <- c(366,359,388,402,427,422,462,524,570,560,578,577)
Recovered <- c(212,240,269,301,320,359,385,413,421,483,516,548)
Death <- c(6,6,7,8,12,14,16,17,17,18,23,25)
day <- itemizeDates(startDate="01.04.20", endDate="12.04.20")

df <- data.frame(Day=day, Infected=Infected, Recovered=Recovered, Death=Death, Total=Total)

value_matrix = matrix(, nrow = 2, ncol = 12)
value_matrix[1,] = df$Recovered
value_matrix[2,] = df$Death

plot(c(1:12), df$Total, ylim=c(0,1200), xlim=c(1,12), type = "b", col="peachpuff", xaxt="n", xlab = "", ylab = "")
points(c(1:12), df$Infected, type = "b", col="red")
barplot(value_matrix, beside = TRUE, col = c("green", "black"), width = 0.35, add = TRUE)

但是条形图不适合折线图。我想使用ggplot2会更容易,但是不知道如何。有人可以帮我吗?在此先多谢!

r ggplot2 bar-chart
1个回答
0
投票

使用ggplot2,可以很好地处理边距,但是您将需要两种单独的长格式的数据。使用tidyr::gathertidyr::pivot_longerreshape2::meltreshape或任何您喜欢的形状从宽变长。

library(tidyr)
library(ggplot2) 

df <- data.frame(
    Total = c(584,605,664,711,759,795,863,954,1008,1061,1117,1150),
    Infected = c(366,359,388,402,427,422,462,524,570,560,578,577),
    Recovered = c(212,240,269,301,320,359,385,413,421,483,516,548),
    Death = c(6,6,7,8,12,14,16,17,17,18,23,25),
    day = seq(as.Date("2020-04-01"), as.Date("2020-04-12"), by = 'day')
)

ggplot(
    tidyr::gather(df, Population, count, Total:Infected), 
    aes(day, count, color = Population, fill = Population)
) + 
    geom_line() + 
    geom_point() + 
    geom_col(
        data = tidyr::gather(df, Population, count, Recovered:Death), 
        position = 'dodge', show.legend = FALSE
    )

“带有线条和条形的图”

另一种方法是在绘制之前先收集两次。不知道这是更容易理解还是更难理解,但是您会得到相同的结果。

df %>% 
    tidyr::gather(Population, count, Total:Infected) %>% 
    tidyr::gather(Resolution, count2, Recovered:Death) %>% 
    ggplot(aes(x = day, y = count, color = Population)) + 
    geom_line() + 
    geom_point() + 
    geom_col(
        aes(y = count2, color = Resolution, fill = Resolution), 
        position = 'dodge', show.legend = FALSE
    )

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS8wcUNOUEpzLnBuZyJ9” alt =“相同图”>

您实际上可以通过分别调用每个点和线来绘制线条和点,而无需重塑形状,但是要躲避小节(或获得图例),肯定需要重塑形状。

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