请原谅我,如果这是一个非常愚蠢的问题。自过去 12 小时以来,我一直在自责,想知道我做错了什么。
我正在尝试使用 ggplot2 中的 facet_grid 和形状来绘制绘图。我正在使用形状在不同年份以不同方式显示点。实际数据集有 7 年的数据点。示例代码数据仅代表 3 年的实际数据。当我不使用形状时,情节是正确的。它在 x 轴上显示正确年份下的点。一旦在 aes 部分中使用了形状,数据点就不是正确的年份。
请帮我解决这个问题。示例代码反映了问题
我在 ubuntu 10.04 LTS 上使用 R 2.14.0 和 ggplot2 0.9.3.1。
library(ggplot2)
library(plyr)
tr_week = c(
"2006-01-16", "2006-01-16", "2006-01-16", "2006-01-16", "2006-01-16",
"2006-01-16", "2007-02-19", "2007-02-19", "2007-02-19", "2007-02-19",
"2007-02-19", "2007-02-19", "2009-08-24", "2009-08-24", "2009-08-24",
"2009-08-24", "2009-08-24", "2009-08-24"
)
tenor = c(
"T00-09", "T10", "T11-14", "T15", "T16-29", "T30", "T00-09", "T10", "T11-14", "T15",
"T16-29", "T30", "T00-09", "T10", "T11-14", "T15", "T16-29", "T30"
)
weeklyTrades = c(
18, 87, 50, 206, 233, 114, 28, 49, 106, 122, 51, 59, 57, 82, 17, 26, 53, 42
)
tr_year = c(
"2006", "2006", "2006", "2006", "2006", "2006", "2007", "2007", "2007", "2007",
"2007", "2007", "2009", "2009", "2009", "2009", "2009", "2009"
)
tr_week = as.Date(tr_week, "%Y-%m-%d")
tenor = factor(tenor)
dfWeek = data.frame(tr_week, tenor, weeklyTrades, tr_year, stringsAsFactors=F)
##### The following plots correctly #############
p = ggplot(dfWeek, aes(tr_week, weeklyTrades, group = 1)) +
ggtitle("Weekly Trades per Tenure Bucket") +
xlab("Trading Week") + ylab("weekly Trades")
p +
facet_grid(tenor ~ ., scale = "free_y") +
geom_point(alpha=0.5, size=1.5)
###### The plot is wrong as soon as shape is specified
q = ggplot(dfWeek, aes(tr_week, weeklyTrades, group = 1, shape = factor(dfWeek$tr_year))) +
scale_shape_manual(name = "Year", values = c(15, 3, 17, 4, 5, 16, 6)) +
ggtitle("Weekly Trades per Tenure Bucket") +
xlab("Trading Week") + ylab("weekly Trades")
q +
facet_grid(tenor ~ ., scale = "free_y") +
geom_point(alpha=0.5, size=1.5)