ggplot equivalent for matplot

2019-04-29 17:09发布

问题:

Is there an equivalent in ggplot2 to plot this dataset? I use matplot, and read that qplot could be used, but it really does not work. ggplot/matplot

data<-rbind(c(6,16,25), c(1,4,7), c(NA, 1,2), c(NA, NA, 1))
as.data.frame(data)
matplot(data, log="y",type='b', pch=1)

回答1:

You can create a similar plot in ggplot, but you will need to do some reshaping of the data first.

library(reshape2)

#ggplot needs a dataframe
data <- as.data.frame(data)
#id variable for position in matrix 
data$id <- 1:nrow(data) 
#reshape to long format
plot_data <- melt(data,id.var="id")


#plot
ggplot(plot_data, aes(x=id,y=value,group=variable,colour=variable)) +
  geom_point()+
  geom_line(aes(lty=variable)) +
  scale_y_log10(breaks=c(1,2,5,10,25))

My output:



回答2:

Try autoplot.zoo. (continued below plot)

library(ggplot2)
library(zoo)

autoplot(zoo(data), facet = NULL) + geom_point()

giving:

Note that if data had column names then the legend would have used them. Also if different line types were wanted then append + aes(linetype = Series). If log10 y axis were desired then append + scale_y_log10() .



回答3:

You can also do it without external packages if you wish:

data <- rbind(c(6,16,25), c(1,4,7), c(NA, 1,2), c(NA, NA, 1))

# set some names (not necessary- helps understand the code):
rownames(data) <- 1:4
colnames(data) <- LETTERS[1:3]
data
   A  B  C
1  6 16 25
2  1  4  7
3 NA  1  2
4 NA NA  1

# convert to data.frame:
d <- as.data.frame.table(data)
d

   Var1 Var2 Freq
1     1    A    6
2     2    A    1
3     3    A   NA
4     4    A   NA
5     1    B   16
6     2    B    4
7     3    B    1
8     4    B   NA
9     1    C   25
10    2    C    7
11    3    C    2
12    4    C    1

ggplot(d, aes(x = Var1, y = Freq, group = Var2, colour = Var2)) + 
  geom_point() +
  geom_line(aes(lty = Var2)) +
  scale_y_log10(breaks = c(1,2,5,10,25))


标签: r ggplot2