Home > database >  Make ggplot2 graph based on a matrix
Make ggplot2 graph based on a matrix

Time:03-15

I try to make ten lines using ggplot2, the data is from a 15*10 matrix and I want to plot line 1 using the first column of matrix, line 2 using the second column of matrix, etc. My code looks like this, but the output is really weird.

The code is:

prop_df <- data.frame(prop_combined)
colnames(prop_df) <- c('Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Qinf', 'Qhyb')
prop_df <- stack(as.data.frame(prop_combined))
prop_df$x <- (rep(seq_len(nrow(prop_combined)), ncol(prop_combined))-1)/10


ggplot(data = prop_df, aes(x = x, y = values), group = ind)  
  geom_line()  
  geom_point()  
  labs(color='Gamma')  
  ylim(0, 80)  
  xlab(TeX("$tau$"))  
  ylab("Power")

The prop_df looks like:

    values  ind   x
1      8.6   Q1 0.0
2     10.7   Q1 0.1
3     11.8   Q1 0.2
4     11.2   Q1 0.3
5     13.0   Q1 0.4
6     15.6   Q1 0.5
7     21.4   Q1 0.6
8     25.0   Q1 0.7
9     28.8   Q1 0.8
10    34.2   Q1 0.9
11    39.5   Q1 1.0
12    48.2   Q1 1.1
13    55.2   Q1 1.2
14    61.6   Q1 1.3
15    67.2   Q1 1.4
16    71.7   Q1 1.5
17     8.8   Q2 0.0
18    11.0   Q2 0.1
19    10.7   Q2 0.2

And the output is: output

CodePudding user response:

In addition to @Freguglia's suggestions, I made some changes to create a clear plot. I used the Cairo() library to name the x axis.

Sample code:

library(ggplot2)
library(Cairo) # to define the greek letters

prop_df <- data.frame(prop_df)
#colnames(prop_df) <- c('Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Qinf', 'Qhyb') # for this example you don't need this line

#prop_df <- stack(as.data.frame(prop_combined)) # this was already 
#prop_df$x <- (rep(seq_len(nrow(prop_combined)), ncol(prop_combined))-1)/10  

prop_df$values=factor(prop_df$values, levels=c("8.6","8.8", "11", "10.7", "11.2", "11.8", "13", "15.6" ,"21.4" ,"25", "28.8", "34.2", "39.5", "48.2", "55.2", "61.6", "67.2", "71.7"))
prop_df$x=factor(prop_df$x, levels=c("0", "0.1","0.2","0.3","0.4","0.5","0.6","0.7","0.8","0.9","1","1.1","1.2","1.3","1.4","1.5"))

ggplot(data = prop_df, aes(x = x, y = values, group = ind))  
       geom_line(lwd=2)  
       geom_point(aes(color=ind), size=6)  
       labs( y="Power",color="Conditions", x=paste(expression("\u03A4")))  
       theme_minimal()

Plot:

enter image description here

Sample data:

values=c(8.6,10.7, 11.8, 11.2, 13.00,15.6,21.4, 25.00, 28.8,34.2, 39.5, 48.2, 55.2,61.6,67.2, 71.7,8.8, 11.00, 10.7)
x=c(0, 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5, 0.00, 0.1, 0.2)
ind=c("Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q1","Q2","Q2","Q2")

prop_df<-cbind(values, ind,x)
  • Related