首页 > 解决方案 > 是否有一个函数可以绘制在 x 轴上具有年份和在 y 轴上具有值的条形图?

问题描述

我有这个数据:

Year    A    B      C       D       E
Y2000   6.8  5.3    36.7    41      10.2
Y2001   2   10.6    40.3    37.8    9.3
Y2002   2.2  8.8    38      40.6    10.5
Y2003   2.3 14.2    41.6    33.8    8.1
Y2004   2.9  6.8    42.3    38.3    9.7
Y2005   5.5 11.9    39.1    43.4    NA
Y2006   6.4  8.6    32.4    41.1    11.4
Y2007   7.7 13.7    29.6    38.9    10
Y2008   9   10.4    36.5    38.8    5.2
Y2009   NA    NA    50.9    49.1    NA

和代码

attach(Data)
mydata <- factor(format(seq(as.Date('2020-01-01'), length.out=10, by='1 year'),'%Y'),
                 levels = format(seq(as.Date('2020-01-01'), length.out=10, by='1 year'),'%Y'),
                 ordered = T)

colnames(Data) <- c("A", "B", "C", "D", "E")

library(ggplot2)
library(reshape2)
xym <- melt(mydata)

ggplot(xym, aes(x = Data$Year, y = value)) +
      theme_bw() +
      scale_fill_brewer(palette = "Set1") + 
      theme(legend.position = "right", axis.text.x = element_text(angle = 90,vjust = 0.2)) +
      geom_bar(stat = "identity", position = "dodge") +
      geom_bar(fill = c("green", "blue", "red", "yellow", "black")))

我正在努力获得我想要的情节。它应该类似于这个问题中的图: Barplot custom

标签: rbar-chart

解决方案


这就是您如何获得与您链接的条形图类似的条形图。我留下了您在示例中设置的所有设置。

library(ggplot2)
library(tidyr)

Data <- tibble::tribble(
    ~Year,    ~A,    ~B,      ~C,       ~D,       ~E,
    "Y2000",   6.8,  5.3,    36.7,    41,      10.2,
    "Y2001",   2,   10.6,    40.3,    37.8,    9.3,
    "Y2002",   2.2,  8.8,    38,      40.6,    10.5,
    "Y2003",   2.3, 14.2,    41.6,    33.8,    8.1,
    "Y2004",   2.9,  6.8,    42.3,    38.3,    9.7,
    "Y2005",   5.5, 11.9,    39.1,    43.4,    NA,
    "Y2006",   6.4,  8.6,    32.4,    41.1,    11.4,
    "Y2007",   7.7, 13.7,    29.6,    38.9,    10,
    "Y2008",   9,   10.4,    36.5,    38.8,    5.2,
    "Y2009",   NA,    NA,    50.9,    49.1,    NA
)


Data %>%
    pivot_longer(-Year) %>% 
    
    ggplot(aes(x = Year, y = value, fill = name)) +
    geom_bar(stat = "identity", position = "dodge") +
    theme_bw() +
    scale_fill_brewer(palette = "Set1") + 
    theme(legend.position = "right", axis.text.x = element_text(angle = 90,vjust = 0.2))

在此处输入图像描述 我不知道你是否也想复制标签。


推荐阅读