简体   繁体   中英

How to draw bar chart in R, based on Levels?

I will put my data first, to better understand the question:

amount    city    agent    address
1         Madras  Vinod    45/BA
2         Kalkta  Bola     56/AS
3         Mumbai  Pavan    44/AA
4         Tasha   Barez    58/SD
5         Tasha   Khan     22/AW
6         Madras  Baaz     56/QE
7         Mumbai  Neer     99/CC
8         Mumbai  Bazan    97/DF

I am learning R. In a scenario, I want to calculate the total numbers of amount in a specific city and then draw a bar chart for that, showing all cities. Considering the data above, I want something like this:

amount    city    
7         Madras  
2         Kalkta  
18        Mumbai  
9         Tasha   

After some searching I found that aggregate function can help, but I faced a problem that says the length is not the same.

Would you please tell me, how can I achieve this?

base R

res <- do.call(rbind,
  by(dat, dat$city, FUN = function(z) data.frame(city = z$city[1], amount = sum(z$amount)))
)
barplot(res$amount, names.arg=res$city)

样本条形图

tidyverse

library(dplyr)
res <- dat %>%
  group_by(city) %>%
  summarize(amount = sum(amount))
barplot(res$amount, names.arg=res$city)

Data

dat <- structure(list(amount = 1:8, city = c("Madras", "Kalkta", "Mumbai", "Tasha", "Tasha", "Madras", "Mumbai", "Mumbai"), agent = c("Vinod", "Bola", "Pavan", "Barez", "Khan", "Baaz", "Neer", "Bazan"), address = c("45/BA", "56/AS", "44/AA", "58/SD", "22/AW", "56/QE", "99/CC", "97/DF")), class = "data.frame", row.names = c(NA, -8L))

Another way to do it using the tidyverse

amount <- c(1,2,3,4,5,6,7,8)
city <- c("Madras", "Kalkta", "Mumbai", "Tasha", "Tasha", "Madras", "Mumbai", 
"Mumbai")

df <- tibble(amount = amount, city = city)

df %>% 
    group_by(city) %>% 
    summarise(amount = sum(amount, na.rm = T)) %>% 
    ggplot(aes(x = city, y = amount)) +
    geom_col() +
    geom_label(aes(label = amount)) +
    theme_bw()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM