简体   繁体   中英

How to plot a bar chart with each x-lab bar contain both positive and negative y values in ggplot r?

I have a sample dataset like this:

df_test <- data.frame(
  proj_manager = c('Emma','Emma','Emma','Emma','Emma','Alice','Alice'),
  proj_ID = c(1, 1, 2, 2, 2, 3, 4), 
  stage = c('B','B','B','A','C','A','C'),
  value = c(15,15,20,20,20,70,5)
)

I calculate the total value of project by manager; and the number of project by stage/manager, and use 'input' for viz:

input <- select(df_test, proj_manager, proj_ID, stage, value) %>%
  filter(proj_manager=='Emma') %>%
  do({
    proj_value_by_manager = sum(distinct(., proj_ID, value)$value);
    mutate(., proj_value_by_manager =  proj_value_by_manager)
  }) %>%
  group_by(stage) %>%
 mutate(count_proj = length(unique(proj_ID))) 

print(input)


proj_manager proj_ID  stage value proj_value_by_manager count_proj
        <fctr>   <dbl> <fctr> <dbl>                 <dbl>      <int>
1         Emma       1      B    15                    35          2
2         Emma       1      B    15                    35          2
3         Emma       2      B    20                    35          2
4         Emma       2      A    20                    35          1
5         Emma       2      C    20                    35          1

I am expecting to draw a bar chart showing selected manager's proj summary with:

  1. X-axis using stage column
  2. Count of project number on positive y-axis
  3. Sum of project value on negative y-axis(but showing a positive value)
  4. The ends of bars for a specific stage joined

( Pic not using the sample data and I am expecting bar chart not boxplot ): 在此处输入图片说明

How can I achieve this using ggplot barchart? Any help will be highly appreciated!!

You will have to work on that, but here is a beginning (the /30 is there just to make the scales comparable, change it to what you need).

df <- data.frame(input)

commapos <- function(x, ...) {
  format(abs(x), big.mark = ",", trim = TRUE,
     scientific = FALSE, ...) }


ggplot (input, aes(stage), stat = "identity") + 
geom_bar()+geom_bar(aes(y=-proj_value_by_manager/30.0), 
stat = "identity", fill = "Blue") + scale_y_continuous(labels = commapos)

That gives you this barebone graphs. Work on it, I am sure you can easily make it prettier...

在此处输入图片说明

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