I am doing a chart in R kind 'Multiple Lines in a Line Chart', and I want to plot 6 vectors with 5 numbers each in the same chart.
The problem is that I do not plot more than 2 lines, when I try to plot the 3rd line, it does not show me anything.
it1 <- c(1406, 1504, 1623, 1405, 1447)
it2 <- c(1565, 1496, 1555, 1590, 1555)
it3 <- c(459, 534, 534, 626, 626)
it4 <- c(642, 643, 482, 661, 651)
it5 <- c(538, 558, 456, 393, 551)
it6 <- c(521, 517, 466, 456, 496)
plot(it1,type="l",col="red")
lines(it2, col="green")
lines(it3, col="blue") #bad
What problem do I have?
It's not showing up because it3
falls entirely below your axis range that was set by the first plot. When adding subsequent plots like this, it doesn't rescale the axis, but uses the axis scaled to the first plot. You can manually specify your axis range in your first plot and then all will show up; however, I would suggest using something like ggplot2
to do this.
plot(it1,type="l",col="red", ylim = c(0, 1800))
lines(it2, col="green")
lines(it3, col="blue") #now works
If you wanted to do it with the commonly used ggplot2
package, you would have to reshape your data into long format. There's several packages that are commonly used for this like tidyr
and reshape2
. It would look something like this:
it_lines <- data.frame(it1,it2,it3,it4,it5,it6)
it_lines$index <- row.names(it_lines)
# Reshape into long format for ggplot2 - requires tidyr, but can be done
# with other approaches like reshape2's melt/cast
it_lines <- tidyr::gather(it_lines, key = it, value = value, it1:it6)
# Plot
library(ggplot2)
ggplot(it_lines, aes(x = index, y = value, group = it, colour = it)) +
geom_line()
Try matplot
it1 <- c(1406, 1504, 1623, 1405, 1447)
it2 <- c(1565, 1496, 1555, 1590, 1555)
it3 <- c(459, 534, 534, 626, 626)
it4 <- c(642, 643, 482, 661, 651)
it5 <- c(538, 558, 456, 393, 551)
it = data.frame(it1, it2, it3, it4, it5)
matplot(it, type = c("b"),pch=1,col = 1:5)
legend("center", legend = 1:5, col=1:5, pch=1)
EDIT: to plot legend outside of plot define x
and y
coordinates outside of the plot. Check ?legend
for more options.
par(xpd=TRUE)
matplot(it, type = c("b"),pch=1,col = 1:5)
legend(x = 2, y = 1850, legend = 1:5, col=1:5, pch=1, horiz= T)
Or you could simply use ggplot2
and some tidyverse
tools to plot them all and make something that looks nicer than matplotlib
:
it1 <- c(1406, 1504, 1623, 1405, 1447)
it2 <- c(1565, 1496, 1555, 1590, 1555)
it3 <- c(459, 534, 534, 626, 626)
it4 <- c(642, 643, 482, 661, 651)
it5 <- c(538, 558, 456, 393, 551)
it6 <- c(521, 517, 466, 456, 496)
library(tidyverse)
data <- tibble(index = 1:5, it1,it2,it3,it4,it5,it6) %>%
gather(var, value, -index)
ggplot(data, aes(x = index, y = value, colour = var)) +
geom_line()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.