更改 ggplot2 中图例的标题会创建第二个图例?

问题描述 投票:0回答:1

我对 R/处理数据还很陌生,我正在尝试更改我制作的可视化中图例的标题。我尝试过在我拥有的

fill=
函数中使用
labels()
,但由于某种原因它添加了另一个图例。我四处寻找解决方案并发现这篇文章但是这两个解决方案都没有解决我的问题。

这是我最初的代码以及它所做的可视化:

data_2023_2 %>% 
  group_by(rideable_type, member_type) %>%
  dplyr::summarize(total_trips = n()) %>% 
  ggplot(aes(x=rideable_type, y=total_trips, fill=member_type, color=member_type)) +
  geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) +
  geom_text(aes(label = total_trips), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") +
  scale_fill_manual(values=c("darkorchid","darkseagreen")) +
  scale_color_manual(values=c("darkorchid","darkseagreen")) +
  theme_bw()+
  labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides")

Viz With Bad Legend Title

然后这是添加了

fill=
的代码

data_2023_2 %>% 
  group_by(rideable_type, member_type) %>%
  dplyr::summarize(total_trips = n()) %>% 
  ggplot(aes(x=rideable_type, y=total_trips, fill=member_type, color=member_type)) +
  geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) +
  geom_text(aes(label = total_trips), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") +
  scale_fill_manual(values=c("darkorchid","darkseagreen")) +
  scale_color_manual(values=c("darkorchid","darkseagreen")) +
  theme_bw()+
  labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides", fill="Member Type")

Viz With 2 Legends But One of Them Has The Good Title I Want

r ggplot2 visualization legend data-analysis
1个回答
0
投票

您可以在实验室功能中执行此操作,如下所示:

data_2023_2 %>% 
  group_by(rideable_type, member_type) %>%
  dplyr::summarize(total_trips = n()) %>% 
  ggplot(aes(x=rideable_type, y=total_trips, fill=member_type)) +
  geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) +
  geom_text(aes(label = total_trips, fill = member_type), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") +
  scale_fill_manual(values=c("darkorchid","darkseagreen")) +
  theme_bw() +
  labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides", fill="Member Type")
© www.soinside.com 2019 - 2024. All rights reserved.