如何解决一年中在数据框架中的四个季度Q1,Q2,Q3和Q4中绘制两列之间的差异时出现问题 数据
我在绘制多样性图时遇到问题,该图向我显示了数据农场一年中四个季度的两列之间的差异。这是我拥有的数据框:
df_Total2 =
Quarters X1 X2
1 Q1 390000 375000
2 Q1 675000 693000
3 Q1 350000 346000
4 Q1 950000 925000
5 Q2 395000 382000
6 Q2 800000 837000
7 Q2 350000 342000
8 Q2 850000 890000
9 Q3 400000 390000
10 Q3 750000 713000
11 Q3 350000 340000
12 Q3 875000 976000
13 Q4 410000 408000
14 Q4 750000 790000
15 Q4 350000 367000
16 Q4 900000 930000
This is my code:
library(plotly)
library(readxl)
df =read_excel("DeptYearlyPerfChange.xls")
df
df_Q1 <- cbind (df$Q1Budget,df$Q1Actual)
df_Q2 <- cbind (df$Q2Budget,df$Q2Actual)
df_Q3 <- cbind (df$Q3Budget,df$Q3Actual)
df_Q4 <- cbind (df$Q4Budget,df$Q4Actual)
df_Total <- rbind (df_Q1,df_Q2,df_Q3,df_Q4)
Quarters <- c ("Q1","Q1","Q2","Q3","Q4","Q4")
df_Total2 <- cbind (Quarters,df_Total)
df_Total2 <- data.frame(Quarters,df_Total)
# Shaded region
ggplot(df_Total2,aes(x=Quarters,y= as.factor(df_Total2[,2]))) +
geom_ribbon(aes(ymin=as.factor(df_Total2[,2])-as.factor(df_Total2[,3]),ymax=as.factor(df_Total2[,2])+as.factor(df_Total2[,3])),alpha=0.2) + geom_line()
我想知道我的代码有什么错误。老实说,我已尽力解决了这个问题,真的需要您的帮助。
解决方法
如果我们需要绘制差异
library(dplyr)
library(ggplot2)
df_Total2 %>%
mutate(Diff = X1 - X2,Sum = X1 + X2) %>%
group_by(Quarters) %>%
mutate(min = min(Diff),max = max(Sum)) %>%
ggplot(aes(x = Quarters,y = X1)) +
geom_ribbon(aes(ymin = first(min),ymax = first(max)),alpha = 0.2) +
geom_line()
数据
df_Total2 <- structure(list(Quarters = c("Q1","Q1","Q2","Q3","Q4","Q4"),X1 = c(390000L,675000L,350000L,950000L,395000L,800000L,850000L,400000L,750000L,875000L,410000L,900000L),X2 = c(375000L,693000L,346000L,925000L,382000L,837000L,342000L,890000L,390000L,713000L,340000L,976000L,408000L,790000L,367000L,930000L)),class = "data.frame",row.names = c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。