简体   繁体   English

如何在ggplot r中绘制每个x-lab条形图同时包含正和负y值的条形图?

[英]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 X轴使用载物台柱
  2. Count of project number on positive y-axis y轴正方向的项目数计数
  3. Sum of project value on negative y-axis(but showing a positive value) y轴上的项目值总和(但显示为正值)
  4. The ends of bars for a specific stage joined 特定阶段的钢筋末端连接

( Pic not using the sample data and I am expecting bar chart not boxplot ): 图片未使用示例数据,我希望条形图不是boxplot ): 在此处输入图片说明

How can I achieve this using ggplot barchart? 如何使用ggplot条形图实现此目标? 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). 您将不得不对此进行操作,但这是一个开始( /30只是为了使比例具有可比性,将其更改为所需的值)。

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... 继续努力,我相信您可以轻松地使其更漂亮...

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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