我正在尝试创建一个像this answer一样的双面条形图,但我想按日期排序条形图并将x轴标签更改为其他值(不是日期)。我的数据集如下:
date rival goals misses
1 2015-07-19 Динамо 2 1
2 2015-07-26 Урал 4 1
3 2015-08-01 Терек 3 0
4 2015-08-09 Уфа 1 0
5 2015-08-15 Краснодар 0 2
6 2015-08-24 Рубин 3 1
7 2015-08-29 Крылья Советов 1 3
8 2015-09-12 ЦСКА 2 2
9 2015-09-20 Амкар 1 1
10 2015-09-26 Спартак 2 2
11 2015-10-03 Ростов 3 0
12 2015-10-17 Кубань 2 2
13 2015-10-24 Анжи 5 1
14 2015-10-31 Мордовия 0 0
15 2015-11-08 Локомотив 0 2
16 2015-11-21 Урал 3 0
17 2015-11-28 Терек 1 4
18 2015-12-03 Уфа 1 1
您可以按此link下载。我使用下一个代码制作图表:
x = read.csv("data/2015-2016.csv", stringsAsFactors = F)
x$date = as.Date(x$date, "%d.%m.%Y")
goalsToMisses = data.frame(
group = c(rep("Goals", nrow(x)), rep("Misses", nrow(x))),
date = rep(x$date, 2),
x = rep(x$rival, 2),
y = c(x$goals, - x$misses),
stringsAsFactors = F
)
ggplot(goalsToMisses, aes(x = reorder(x, date), y = y, fill = group)) +
geom_bar(stat="identity", position="identity") +
ylim(- max(x$goals), max(x$goals)) +
scale_y_continuous(breaks = seq(- max(x$goals), max(x$goals), 1)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 15))
但是排序错了;它应该像在初始数据集中一样,从上到下。我怎么解决它?
更新:与this question的主要区别在于我使用双面条形图和goalsToMisses
数据框比初始数据框多两倍。
此外,我无法在rival
因素上设置级别,因为rival
列包含重复项,并且出现duplicated levels in factors are deprecated
错误。
答案 0 :(得分:1)
应该添加正确级别排序的棘手因素:
x = read.csv("data/2015-2016.csv", stringsAsFactors = F)
x$date = as.Date(x$date, "%d.%m.%Y")
goalsToMisses = data.frame(
group = c(rep("Goals", nrow(x)), rep("Misses", nrow(x))),
x = paste(rep(x$rival, 2), "\n(", rep(x$date, 2), ")", sep=""),
y = c(x$goals, - x$misses),
stringsAsFactors = F)
matches = unique(goalsToMisses$x)
goalsToMisses$x = factor(goalsToMisses$x, levels = matches[order(x$date)])
ggplot(goalsToMisses, aes(x = x, y = y, fill = group)) +
geom_bar(stat="identity", position="identity") +
ylim(- max(x$goals), max(x$goals)) +
scale_y_continuous(breaks = seq(- max(x$goals), max(x$goals), 1)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 15))