如何在R中重新排序点图

5uzkadbs  于 2023-04-03  发布在  其他
关注(0)|答案(2)|浏览(107)

我有一个数据集,关于1992年至1999年期间五个不同城市拥有汽车的个人百分比:

city <- c("A", "A", "B", "B", "F", "F", "T", "T", 
             "C", "C") 
year <- c("1992", "1999", "1992", "1999", "1992", "1999", "1992", "1999", "1992", "1999")
# variable 2
car_owner <- c("15.9", "75.6", "35.8", "95.2", "15.9", "74", "6", "64", "41", "97.9")

df <- data.frame(city, year, car_owner)
df$car_owner <- as.numeric (df$car_owner)

现在我使用这段代码并创建一个点图:

df %>%
  group_by(city) %>%
  mutate(Difference = car_owner - lead(car_owner),
         Position = car_owner - (0.5 * Difference)) %>%
  ggplot(aes(x = car_owner, y = city))+
  geom_vline(xintercept = c(),
             lty = 2, alpha = 0.5) +
  geom_line(aes(group = city)) +
  geom_point(aes(color = year), size=3) +
  geom_text(aes(label = abs(Difference),
                y = city,
                x = Position),
            nudge_y = 0.2) +
  theme_classic(base_size = 12) +
  labs(x = "Car owner)")+
  theme(legend.position = "top") +
  scale_color_brewer(palette = "Accent", direction = ) +
  theme(axis.ticks.y = element_line(colour = c("transparent",
                                               rep("black", 12))))

图中显示了所有的信息。然而,我想做的是根据年份之间差异的大小对图进行排序。因此,A城市应该是第一个(增加59.9个百分点),然后是B,F,T,最后是C。

rkttyhzu

rkttyhzu1#

在绘图前重新排列因子。所以加上

df$city = factor(df$city, lvels=c("A","B","F","T","C"))

在情节之前。

lkaoscv7

lkaoscv72#

使用reorder,您可以通过car_owner的绝对差对city重新排序,如下所示:

library(dplyr)
library(ggplot2)

df_label <- df %>%
  group_by(city) %>%
  summarise(
    Difference = diff(car_owner),
    Position = mean(car_owner)
  )

df %>%
  mutate(city = reorder(city, car_owner, function(x) abs(diff(x)))) %>%
  ggplot(aes(x = car_owner, y = city)) +
  geom_line(aes(group = city)) +
  geom_point(aes(color = year), size = 3) +
  geom_text(
    data = df_label,
    aes(
      label = abs(Difference),
      y = city,
      x = Position
    ),
    nudge_y = 0.2
  ) +
  theme_classic(base_size = 12) +
  labs(x = "Car owner)") +
  theme(legend.position = "top") +
  scale_color_brewer(palette = "Accent", direction = ) +
  theme(axis.ticks.y = element_line(colour = c(
    "transparent",
    rep("black", 12)
  )))

相关问题