[英]Changing order of stacked areas
I am trying to order the stacked geom_area
in an arbitrary way. 我试图以任意方式订购堆叠的
geom_area
。
For instance: 例如:
investments <- data.frame(Date = c(as.Date('2019-01-01'), as.Date('2019-01-01'),
as.Date('2019-01-01'), as.Date('2019-01-02'),
as.Date('2019-01-02'), as.Date('2019-01-02')),
Amount = c(100, 200, 150, 120, 200, 130),
InvestType = c("Shares", "Cash", "Bonds",
"Shares", "Cash", "Bonds"))
ggplot()+
geom_area(data = investments,
aes(x = Date, y = Amount, fill = InvestType))
This gives the above graph with the stacked areas ordered "Shares, Cash, Bonds". 这给出了上面的图表,其中堆叠区域的顺序为“股票,现金,债券”。 Now I want "Cash" to always be on top.
现在,我希望“现金”始终位于最前面。
I tried sorting the dataframe with: 我尝试对数据框进行排序:
investments <- arrange(investments,
factor(InvestType, levels = c("Shares", "Bonds", "Cash")))
This sorted the data frame by InvestType but did not change the order of the stacked areas. 这按InvestType对数据框进行了排序,但未更改堆叠区域的顺序。
@Z.Lin gave the correct answer in the comments. @ Z.Lin在评论中给出了正确答案。 I needed the stacked area variable to be a factor and have the levels set in the right order.
我需要堆积面积变量作为一个因素,并以正确的顺序设置级别。 Converted using
investments$InvestType <- factor(investments$InvestType, levels = c("Shares", "Bonds", "Cash"))
before plotting as per the comment. 在根据注释进行打印之前
investments$InvestType <- factor(investments$InvestType, levels = c("Shares", "Bonds", "Cash"))
使用investments$InvestType <- factor(investments$InvestType, levels = c("Shares", "Bonds", "Cash"))
进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.