简体   繁体   English

使用多列作为 R 的 ggplot2 中的 x 轴

[英]Utilising multiple columns to be the x-axis in ggplot2 for R

Desired graph想要的图

I wanted to obtain the above graph, and I tried using ggplot for it.我想获得上面的图表,我尝试使用 ggplot 来获取它。

blue = c(83, 81, 80, 71, 69, 63, 63, 62, 54)
red = c(112, 96, 111, 141, 125, 89, 178, 107, 130)
loc = c("YISHUN", "WOODLANDS", "HOUGANG", "ANG MO KIO"  "TAMPINES", "SENGKANG", "GEYLANG", "BEDOK", "JURONG WEST")
tib = mutate(blue, red, loc)
ggplot(lst_compare, aes(x=c(wet, dry) ,y=loc)) +
  geom_point() + geom_segment(y=loc, x= wet, xend= dry, yend= loc)

I tried the above method, however, it seems I can't simply include multiple columns as the x value.我尝试了上述方法,但是,似乎不能简单地将多列包含为 x 值。 Does anyone know how to include multiple columns as part of x-axis?有谁知道如何将多列作为 x 轴的一部分?

I fixed the mistakes in your reprex.我修正了你的 reprex 中的错误。 I think it's best to pivot the data before plotting.我认为最好在绘图之前对数据进行透视。

library(tidyverse)
blue = c(83, 81, 80, 71, 69, 63, 63, 62, 54)
red = c(112, 96, 111, 141, 125, 89, 178, 107, 130)
loc = c("YISHUN", "WOODLANDS", "HOUGANG", "ANG MO KIO",  "TAMPINES", "SENGKANG", "GEYLANG", "BEDOK", "JURONG WEST")
tib = data.frame(blue, red, loc)

tib %>% 
  pivot_longer(c("blue", "red")) %>% 
  ggplot() +
  geom_point(aes(x = value, y = loc, color = name), size = 2) +
  scale_color_identity() +
  geom_line(aes(x = value, y = loc)) + 
  theme_minimal()

Created on 2021-10-21 by the reprex package (v2.0.1)reprex 包(v2.0.1) 于 2021 年 10 月 21 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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