0

I have these piece of code to draw two line charts ( confirmed cases and death cases) How to show both curves in one chart with two dataframes (two ggplots)? Is it even possible or do I need to merge my two dataframes ( conf_data, dead_data ) into one data_frame ?

ggplot(conf_data, aes(x = date, y = confirmed)) +
        geom_line(colour = "blue", size =1.1, aes(date, confirmed)) +
        scale_y_continuous(labels = comma)

  ...

      ggplot(dead_data, aes(x = date, y = deaths)) +
        geom_line(colour = "red", size =1.1, aes(date, deaths)) +
        scale_y_continuous(labels = comma)

Here is my current working example with just one chart http://webcovid19.online/

2
  • It’s possible — but why not join the data? 9 out of 10 times that’s what you want to do. Commented Nov 25, 2020 at 14:16
  • yes, you have right, join is the best option ( also for performance, I hope) , but as you advised me also two dataframes option is working, let me check... :) Commented Nov 25, 2020 at 14:45

2 Answers 2

1

Does this work

library(tidyverse)

ggplot(conf_data, aes(x = date, y = confirmed)) +
        geom_line(colour = "blue", size =1.1, aes(date, confirmed)) +
        geom_line(colour = "red", size =1.1, aes(date, deaths)) +
        scale_y_continuous(labels = comma)
Sign up to request clarification or add additional context in comments.

Comments

0

You can pass custom data to a geometry via the data argument:

ggplot(conf_data, aes(x = date, y = confirmed)) +
    geom_line(color = "blue", size = 1.1, aes(date, confirmed)) +
    scale_y_continuous(labels = comma) +
    geom_line(color = "red", size = 1.1, aes(date, deaths), data = dead_data)

However, most of the time it’s more convenient to merge the data prior to plotting — if for no other reason, then because it allows you to create a proper legend and provide custom colour scales etc.:

bind_rows(
    transmute(conf_data, number = confirmed, type = 'confirmed'),
    transmute(death_data, number = deaths, type = 'deaths')
) %>%
    ggplot(aes(x = date, y = number, color = type, group = type)) +
    geom_line()

2 Comments

Hi Rudolph, I already use the 2nd option ( join dataframes ..), however is there some option to filter in multi charts ( countries in my case) to show only top 10 lines, to speed up ggplot ? Or I have to do it my self, filter dataframes before ggplot ? ( I did it already this way, see my site.)
@Andrew Unfortunately you have to do the filtering yourself, I’m not aware of an option inside ‘ggplot2’ to do the filtering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.