1

I am trying to create a line chart in R Base where I have two lines. One is for population growth in Oslo and the other one for population growth in Tromso.

However my code only produce one line.

# 1. Read data (comma separated)
res = read.csv2(text = "X-Years;Y-Oslo;Y-Tromso
2017;666757;74541
2018;673469;75638
2019;681071;76000
2020;693556;77000
2021;697057;78000")

# Create Line Chart

# convert factor to numeric for convenience
number_of_x <- length(res[ , 1:1])

# get the range for the x and y axis
x_range <- res[ , 1:1] # Years: 2017 2021
y_range1 <- res[ ,2:2] 
y_range2 <- res[ , 3:3]

x_range
y_range1
y_range2

# set up the plot
plot(x_range, y_range1, 
     type="l", 
     xlab="Years",
     ylab="Population")
lines(x_range, y_range2, type="b") 
title("Population Growth")

Output: enter image description here

Europa
  • 974
  • 12
  • 40
  • This might be helpful https://stackoverflow.com/questions/14860078/plot-multiple-lines-data-series-each-with-unique-color-in-r – Ronak Shah May 16 '21 at 07:33

1 Answers1

1

Its because your y_range1 and y_range2 have completely different value ranges. You can bring both lines into a single plot using ylim argument. For example:

plot(x_range, y_range1, 
     type="l", 
     xlab="Years",
     ylab="Population",
     ylim = c(range(y_range2)[1], range(y_range1)[2]))
lines(x_range, y_range2, type="b") 
title("Population Growth")

enter image description here

Note: range(y_range2)[1] is your smallest value in y_range2 and range(y_range1)[2] is the biggest value in y_range1. If you want both of these lines to appear in your plot, you need to make sure that your ylim is in the right range.

bird
  • 2,938
  • 1
  • 6
  • 27
  • Is it possible to not hard code the ylim value? Because I want to get the data from a csv file in the future. – Europa May 16 '21 at 07:55
  • 1
    @Europa please see the updated plot and code. There was a small typo that flipped the `y-axis`. Now the plot looks better. – bird May 16 '21 at 08:30