在R中创建正负条形图

布莱恩·D

我有一个数据框,x5,我想创建一个正负条形图,其数据类似于stackoverflow的问题:Stackoverflow的问题

我试图使用下面显示的一些代码:

ggplot(x5, aes(reorder(x5[, 1], -x5[, 3]), x5[, 3], fill = class))

我不断收到以下错误消息。我猜这是由于列的字符,数字或因素之类的原因。

Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
Error: Aesthetics must be valid data columns. Problematic aesthetic(s): fill = class. 
Did you mistype the name of a data column or forget to add after_stat()?
Run `rlang::last_error()` to see where the error occurred.
> rlang::last_error()

我想要y轴上的第一列(Row.names)标签,想要在该轴的正负两面的第五列(Name)名称标题,具体取决于它是正数还是负数(如题)。我还希望最高的阴影较暗,最低的阴影较浅(如果可能)。


dput(x5):

structure(list(Row.names = structure(c("X1a", "X2b", "X3c"), class = "AsIs"), Volatility101 = c(40, 
30, 20), `2020-12-08` = c(-15, 
24, 27), cluster = structure(c(1L, 
1L, 2L), .Label = c("1", 
"2", "3"), class = "factor"), Name = structure(1:3, .Label = c("ONE", 
"TWO", "Three"), class = "factor"), 
    `12m yield` = c("0.12", "0.44", "2.20"), `Price to forecast PE` = c("7", 
    "12", "8")), row.names = c(NA, -3L
), class = "data.frame")

下一种方法可以引导您走上正确的道路:

library(ggplot2)
#Data
x5$Var <- as.character(x5$Row.names)
#Plot
ggplot(x5,aes(x=Var,y=`2020-12-08`,fill=Name))+
  geom_bar(stat = 'identity')+
  geom_text(aes(x=Var,y=ifelse(`2020-12-08`<0,2,-2),
                label=Name),vjust=0.5)+
  coord_flip()

输出:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章