简体   繁体   中英

Scatter plot for multiple variables on x axis

I want to create a scatter plot for multiple variables defined in different columns. sample input:

df=structure(list(section = structure(1:6, .Label = c("a", "b", 
"c", "d", "e", "f"), class = "factor"), level = c(0L, 1L, 2L, 
1L, 2L, 0L), math.av = c(83L, 67L, 76L, 56L, 72L, 76L), science.av = c(75L, 
76L, 82L, 72L, 82L, 68L), language.av = c(80L, 75L, 80L, 73L, 
85L, 70L)), class = "data.frame", row.names = c(NA, -6L))

I want the x axis to be divided for each of the 3 different columns of the subjects, and the y axis to be representing their different values.

I have to group them in colors with another column as an indicator which in this case, according to the level

Here is an approach with dplyr and ggplot2 .

First, we need to pivot the data to be long instead of wide.

library(dplyr)
library(tidyr)
long_df <- df %>% pivot_longer(-c(section,level))

Then we can graph a dotplot.

library(ggplot2)
ggplot(long_df, aes(x=as.factor(name),y=value,fill=as.factor(level))) +
  geom_dotplot(binaxis='y') +
  labs(x="Subject") +
  guides(fill = guide_legend(title = "Level"))

在此处输入图片说明

Data

df <- structure(list(section = structure(1:6, .Label = c("a", "b", 
"c", "d", "e", "f"), class = "factor"), level = c(0L, 1L, 2L, 
1L, 2L, 0L), math.av = c(83L, 67L, 76L, 56L, 72L, 76L), science.av = c(75L, 
76L, 82L, 72L, 82L, 68L), language.av = c(80L, 75L, 80L, 73L, 
85L, 70L)), class = "data.frame", row.names = c(NA, -6L))

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