Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

image - Create a geom_bar, and color each bar based on how many times the word is said by each account

I have a dataframe and I need to create a bar plot of the most frequently used words, using the ggplot function. I would like to color each bar based on how many times users say that word.

name <- c('Luca', 'Marco','Alberto', 'Luca', 'Marco')
word <- c('pizza', 'cola', 'pizza','cola','pizza')
count <- c(3,5,6,4,1)
total_count <- c (10, 9,10,9,10)
df <- data.frame(name,word,count,total_count)

The count column indicates how many times the word is said by that person (name). Total_count instead indicates how many times the word is said in total (regardless of who says it).

Here's an image as an example of how it should look.

https://i.stack.imgur.com/AZNQc.png


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

1 Answer

0 votes
by (71.8m points)

geom_bar expects un-summarized data similar to the following

  name    word 
   <fct>   <fct>
 1 Luca    pizza
 2 Luca    pizza
 3 Luca    pizza
 4 Marco   cola 
 5 Marco   cola 
 6 Marco   cola 
 7 Marco   cola 
 8 Marco   cola 
 9 Alberto pizza
10 Alberto pizza
11 Alberto pizza
12 Alberto pizza
13 Alberto pizza
14 Alberto pizza
15 Luca    cola 
16 Luca    cola 
17 Luca    cola 
18 Luca    cola 
19 Marco   pizza

You data is already summarized since it has the count column. To create a bar graph from summarized data you can use geom_col

name <- c('Luca', 'Marco','Alberto', 'Luca', 'Marco')
word <- c('pizza', 'cola', 'pizza','cola','pizza')
count <- c(3,5,6,4,1)
total_count <- c (10, 9,10,9,10)
df <- data.frame(name,word,count,total_count)

ggplot(df, aes(y=word, x=count, fill=name)) + 
  geom_col()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...