【问题标题】:use ggplot2 to make a bar chart使用ggplot2制作条形图
【发布时间】:2021-04-24 06:16:39
【问题描述】:

我的数据看起来像这样,我想创建一个条形图

     services percent
1     overall  80.00%
2   service 1  50.00%
3   service 2  43.00%
4   service 3  45.00%
5   service 4  78.00%
6   service 5  34.00%
7   service 6  78.00%
8   service 7  23.00%
9   service 8  54.00%
10  service 9  32.00%
11 service 10  32.00%

这是我尝试过的

ggplot(service, aes(fill=services, y=percent, x=services)) + 
  geom_bar(position="dodge", stat="identity") + 
  coord_flip() 

现在我想修改图表

  1. y 轴保持原顺序
  2. 删除图例
  3. 将 x 轴强制为 100% 比例

【问题讨论】:

标签: r ggplot2 bar-chart


【解决方案1】:

试试这个:

library(ggplot2)
library(dplyr)
#Code
df %>%
  mutate(percent=as.numeric(gsub('%','',percent))/100,
         services=factor(services,levels = rev(unique(services)),ordered = T))%>%
  ggplot(aes(fill=services, y=percent, x=services)) + 
  geom_bar(position="dodge", stat="identity") +
  scale_y_continuous(labels = scales::percent,limits = c(0,1))+
  coord_flip()+
  theme(legend.position = 'none')

输出:

使用的一些数据:

#Data
df <- structure(list(services = c("overall", "service 1", "service 2", 
"service 3", "service 4", "service 5", "service 6", "service 7", 
"service 8", "service 9", "service 10"), percent = c("80.00%", 
"50.00%", "43.00%", "45.00%", "78.00%", "34.00%", "78.00%", "23.00%", 
"54.00%", "32.00%", "32.00%")), row.names = c(NA, -11L), class = "data.frame")

【讨论】:

  • @Dr.KnowNothing 总是乐于助人。由于您是新手,请查看this useful information 了解下一步该做什么。亲切的问候!
  • 只是一个后续问题,我怎样才能保持 y 轴的原始顺序?喜欢从上到下“总体,服务 1,......服务 10”?
  • @Dr.KnowNothing 我现在就更新代码!
  • @Dr.KnowNothing 我已经为你更新了代码。请检查并让我知道这是否适合您。还要检查我与您分享的信息!
  • 完美。非常感谢!我会弄清楚每一行代表什么!这非常有帮助!
猜你喜欢
  • 2023-03-27
  • 2017-09-27
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多