使用ggplot2创建一个折线图,显示每个观察中两个变量之间的差异

时间:2017-06-02 00:49:42

标签: r ggplot2

这是我的数据:

   Assignment first Stage  Grade Type
1        PA06  98.5 final  98.50   PA
2        PA06  98.5 final  98.50   PA
3        PA06  83.0 final  83.00   PA
4        PA06 100.0 final 100.00   PA
5        PA06 100.0 final 100.00   PA
6        PA06  98.5 final  98.50   PA
7        PA06  86.0 final  86.00   PA
8        PA06 100.0 final 100.00   PA
9        PA06  84.5 final  88.00   PA
10       PA06  95.0 final  95.00   PA
11       PA06  83.0 final  90.00   PA
12       PA06   0.0 final   6.75   PA

我想我想要一张沿x轴观察的图表,显示一条从“第一”开始到“年级”结束的垂直线。

请注意,通常首先和成绩相等,在这种情况下我只得到一个点。否则我会在每一端都有一个带点的线。我想在x轴上没有标签。

这可能有点奇怪,但我正在试验我的数据。我认为这应该是“容易的”,但我似乎无法得到它。这是我到目前为止所尝试的内容:

ggplot(x2, aes(x=first, y=Grade)) + geom_line()
ggplot(x2, aes(x=email)) + geom_point(aes(y=Grade, col="blue")) + geom_point(aes(y=first, col="red"))

2 个答案:

答案 0 :(得分:2)

使用geom_dumbbell()包中的ggalt

mydf$case <- 1:nrow(mydf)

library(ggplot2)
library(ggalt)

ggplot(mydf, aes(first, case, xend = Grade)) +
   geom_dumbbell(size_x = 2, size_xend = 2) +
   coord_flip() +
   theme(axis.ticks.x = element_blank(),
         axis.text.x = element_blank(),
         axis.title.x = element_blank()) 

数据:

mydf <- read.table(text="Assignment first Stage  Grade Type
1        PA06  98.5 final  98.50   PA
2        PA06  98.5 final  98.50   PA
3        PA06  83.0 final  83.00   PA
4        PA06 100.0 final 100.00   PA
5        PA06 100.0 final 100.00   PA
6        PA06  98.5 final  98.50   PA
7        PA06  86.0 final  86.00   PA
8        PA06 100.0 final 100.00   PA
9        PA06  84.5 final  88.00   PA
10       PA06  95.0 final  95.00   PA
11       PA06  83.0 final  90.00   PA
12       PA06   0.0 final   6.75   PA", header = TRUE)

答案 1 :(得分:1)

# Load package
library(tidyverse)
library(data.table)

# Create example data frame
dt <- fread("Assignment first Stage  Grade Type
PA06  98.5 final  98.50   PA
            PA06  98.5 final  98.50   PA
            PA06  83.0 final  83.00   PA
            PA06 100.0 final 100.00   PA
            PA06 100.0 final 100.00   PA
            PA06  98.5 final  98.50   PA
            PA06  86.0 final  86.00   PA
            PA06 100.0 final 100.00   PA
            PA06  84.5 final  88.00   PA
            PA06  95.0 final  95.00   PA
            PA06  83.0 final  90.00   PA
            PA06   0.0 final   6.75   PA")

# Preprocess the data
dt2 <- dt %>%
  # Add ID
  mutate(ID = 1:n()) %>%
  # Reshape the data
  gather(Class, Score, first, Grade)

# Plot the data
dt2 %>%
  ggplot(aes(x = factor(ID), y = Score)) +
  geom_point(aes(colour = Class)) +
  geom_line(aes(group = ID)) +
  scale_x_discrete(name = "")