尝试使用ggplot2在同一克利夫兰点图上绘制两列

时间:2019-05-09 17:03:26

标签: r ggplot2

我的数据中有三列。名称,TP和FP,我想绘制一个克利夫兰点图,该点按TP值(降序排列)显示,同时显示了各个Name的TP和FP值。

R代码

data <- read.csv("averages-names.csv")

data <- data %>% group_by(Name) %>% summarise(TP = sum(TP, na.rm=TRUE), FP = sum(FP, na.rm=TRUE)) %>% arrange(TP) %>% mutate(Name = factor(Name, levels = .$Name))

p = ggplot(data, aes(TP, Name)) + geom_point(color = "blue")
q = ggplot(data, aes(FP, Name)) + geom_point(color = "red")

这在两个单独的图上成功显示了它们,但是我想在同一张图上绘制两个列。

我的数据如下:

data
A tibble: 173 x 3
   Name                                          TP    FP
   <fct>                                      <dbl> <dbl>
 1 Audi S5 Coupe 2012                         0.214 0.633
 2 Chevrolet Express Cargo Van 2007           0.267 0.361
 3 Audi 100 Wagon 1994                        0.317 0.663
 4 Chevrolet Silverado 1500 Extended Cab 2012 0.422 0.633

2 个答案:

答案 0 :(得分:0)

如果您按照以下方式重塑数据,这将变得容易得多:

df <-
  tibble(
    car = c("audi", "chevy", "bmw", "mercedes"),
    TP = c(0.633, 0.361, 0.663, 0.633),
    FP = c(0.214, 0.267, 0.317, 0.422)
  )

df_rev <-
  df %>% 
  gather(key = metric, value = value, TP:FP)

> df_rev
# A tibble: 8 x 3
  car      metric value
  <chr>    <chr>  <dbl>
1 audi     TP     0.633
2 chevy    TP     0.361
3 bmw      TP     0.663
4 mercedes TP     0.633
5 audi     FP     0.214
6 chevy    FP     0.267
7 bmw      FP     0.317
8 mercedes FP     0.422

然后,您可以对图进行最少的调用:

df_rev %>% 
  ggplot(aes(x = value, y = car, color = metric)) +
  geom_point()

答案 1 :(得分:0)

或者如果您只是想保持数据原样。

data <- tibble::tribble(
                                         ~Name,   ~TP,    ~FP,
                          "Audi S5 Coupe 2012", 0.214,  0.633,
            "Chevrolet Express Cargo Van 2007", 0.267,  0.631,
                         "Audi 100 Wagon 1994", 0.317,  0.663,
  "Chevrolet Silverado 1500 Extended Cab 2012", 0.422, 0.6633
  )

library(ggplot2)

ggplot(data ) + 
  geom_point(aes(TP, Name, color = "blue")) + 
  geom_point(aes(FP, Name, color = "red")) +
  labs(x = "metric")