问题
I have a dataset that looks like this:
Year AL AK AZ AR CA CO 1993 135 153 113 157 718 516 1994 218 154 184 185 845 465 1995 482 846 683 682 863 863
I want to plot line graphs over time, so x-axis is year, y-axis is the count and each line would be a state. How can I get the year to show up on the x-axis?
I've been running this:
data <- read.csv("data.csv", header=T)
plot(data$AL, type="l")
par(new=T)
plot(data$AK, type="l")
.....
Except with what I have above, the x-axis is "Index" but I want it to be year.
回答1:
Treat your data as time series and the solution comes very easy:
df <- read.table(text="Year AL AK AZ AR CA CO
1993 135 153 113 157 718 516
1994 218 154 184 185 845 465
1995 482 846 683 682 863 863", header=T)
time.series <- ts(df[, -1], start=1993, end=1995)
plot(time.series, main="Toy example")
which produces
If you want a single panel, then:
plot(time.series, main="Toy example", plot.type="single", col=1:6)
You may want to read ?legend
to get know how to put legends on plots.
回答2:
You may also try to read your data straight to a zoo
object, which then can be plotted.
library(zoo)
z1 <- read.zoo(text = "Year AL AK AZ AR CA CO
1993 135 153 113 157 718 516
1994 218 154 184 185 845 465
1995 482 846 683 682 863 863", header = TRUE)
plot(z1, xlab = "Year")
If you want to plot all lines in the same panel, use plot(z1, plot.type = "single", col = 1:6)
.
来源:https://stackoverflow.com/questions/19595520/how-to-plot-line-graph-in-r-with-years-as-x-axis-and-y-axis-as-count