質問

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.

役に立ちましたか?

解決

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

enter image description here

If you want a single panel, then:

plot(time.series, main="Toy example", plot.type="single", col=1:6)

enter image description here

You may want to read ?legend to get know how to put legends on plots.

他のヒント

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")
 

enter image description here

If you want to plot all lines in the same panel, use plot(z1, plot.type = "single", col = 1:6).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top