简体   繁体   中英

box plot with ggplot2

I am sorry for my basic question. I am new to R and trying to draw a box plot with the following data.

boxplot.csv

group1  group2  group3
5.18    7        4.18
4.61    7.5      3.52
3.3     4.5      1.5
4.56    7.58     3.39
3        4       2.5
3.8     4.67     3.43
1.95    3.5      1
2.67    3        2.6
2.77    3.5      2.17

I can draw the box plot with the following code.

df = read.csv ("/home/bud/Desktop/boxplot.csv")
boxplot(df, col=c("red","blue","green"),main = "my first boxplot", ylim=c(0,10),ylab = "marks")

But I would like to get the same box plot with ggplot2. How can I do that?

put data in long format

library(reshape2)
df <- melt(df)

And then simply

ggplot(data=df, aes(x=variable, y=value, fill=variable)) + 
  geom_boxplot()

You can add layers to define how you want the plot to look, eg

ggplot(data=df, aes(x=variable, y=value, fill=variable)) + 
  geom_boxplot() + 
  theme_bw() +
  labs(x="Group", y="Marks")

to remove the legend you can use either

guides(fill=FALSE)   
## use to turn off one or more legends, 
## depending on your `aes` values. 
## In this example we are only using the `fill` argument

or

theme(legend.position="none")
## removes legend from graph

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM