r - 是否有一个函数可以绘制在 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
解决方案
这就是您如何获得与您链接的条形图类似的条形图。我留下了您在示例中设置的所有设置。
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))
推荐阅读
- node.js - node.js + sequelize 批量插入
- autocomplete - LLDB 自动补全不起作用(Lubuntu)
- python - 从一组图像中丢弃外观相似的图像
- html - Center text inside a div filled with particlesJS
- sql - 从另一个选择中调用带有表参数的标量函数
- javascript - 循环内的 JS 函数 - 内存/CPU注意事项
- vert.x - 如何在 Vert.x JUnit 中使用 Async.await() 而不会遇到“VertxException:线程阻塞”?
- javascript - PHP 邮件程序不起作用
- javascript - 在Javascript中合并对象并添加具有相同键的值
- excel - 在公式范围内设置偏移量以避免过度使用