Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

r - use ggplot2 to make a bar chart

my data looks like this and I want to create a bar plot

     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%

here is what I tried

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

enter image description here

Now I want to revise the chart with

  1. keep the y-axis in the original order
  2. remove the legend
  3. force the x-axis on a 100% scale

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

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')

Output:

enter image description here

Some data used:

#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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...