我正在尝试使用以下代码绘制填充的矩形 -
tplot.old <- ggplot() +
geom_rect(data=t.df,mapping=aes(xmin=xa, xmax=xb, ymin=ya, ymax=yb, fill=Train)) +
ylab("Cars per week") + xlab("Miles") + ggtitle(old.title) +
theme(axis.text.x = element_text(angle=45,size=5,hjust=1), axis.text=element_text(size=5), axis.text.y = element_text(size=5), title=element_text(size=5), legend.text=element_text(size=5)) +
scale_fill_manual(values=color_values) +
scale_x_continuous(breaks=plot.stns$Avg_Miles,labels=plot.stns[,"City_Name"]) +
coord_cartesian(xlim=c(0,1700),ylim=c(0,500))
t.df
看起来像这样:
Train xa xb ya yb col
a MHKNP 407 1594 0 22.806452 red
b MPDNP 407 1594 0 9.258065 darkgreen
cd MHKRO 407 1594 0 5.258065 orange
和plot.stns
:
Avg_Miles City_Name
1 0 EUGENE
4 15 BLAKESLEEJCT
12 64 LONGVIEWJCT
25 118 ALBINA
45 306 HINKLE
当我在控制台上以交互方式绘制时,这似乎有效,但在for循环中出现此错误 -
Error: Discrete value supplied to continuous scale
color_values:
MHKNP MHKNPB MHKPC MHKRO MPCGR MPSHK
"red" "green" "blue" "maroon" "orange" "black"
QCONP QPCNPP MPDNP
"magenta" "skyblue" "darkgreen"
这与scale_x_continuous
有某种关系(当我删除它时它没有给出错误),但我无法弄清楚这里有什么问题。有什么想法吗?
答案 0 :(得分:4)
我在你的两个部分数据框上做了read.table(pipe("pbpaste"))
(我在Mac上),并适度地重构了你的代码。如果数据框列类型与您的不同,可能会粘贴dput
vs ascii表格输出。
但是,我没有得到同样的错误:
t.df <- structure(list(Train = structure(c(1L, 3L, 2L), .Label = c("MHKNP",
"MHKRO", "MPDNP"), class = "factor"), xa = c(407L, 407L, 407L
), xb = c(1594L, 1594L, 1594L), ya = c(0L, 0L, 0L), yb = c(22.806452,
9.258065, 5.258065), col = structure(c(3L, 1L, 2L), .Label = c("darkgreen",
"orange", "red"), class = "factor")), .Names = c("Train", "xa",
"xb", "ya", "yb", "col"), class = "data.frame", row.names = c("a",
"b", "cd"))
plot.stns <- structure(list(Avg_Miles = c(0L, 15L, 64L, 118L, 306L), City_Name = structure(c(3L,
2L, 5L, 1L, 4L), .Label = c("ALBINA", "BLAKESLEEJCT", "EUGENE",
"HINKLE", "LONGVIEWJCT"), class = "factor")), .Names = c("Avg_Miles",
"City_Name"), class = "data.frame", row.names = c("1", "4", "12",
"25", "45"))
color_values = t.df$col
gg <- ggplot(data=t.df, mapping=aes(xmin=xa, xmax=xb, ymin=ya, ymax=yb, fill=Train))
gg <- gg + geom_rect()
gg <- gg + labs(y="Cars per week", x="Miles", title="(old.title)")
gg <- gg + scale_fill_manual(values=color_values)
gg <- gg + scale_x_continuous(breaks=plot.stns$Avg_Miles,
labels=plot.stns[,"City_Name"])
gg <- gg + coord_cartesian(xlim=c(0, 1700), ylim=c(0,500))
gg <- gg + theme(axis.text.x = element_text(angle=45, size=5, hjust=1),
axis.text = element_text(size=5),
axis.text.y = element_text(size=5),
title = element_text(size=5),
legend.text = element_text(size=5))
gg
“old.title”丢失了,所以我只是把它作为文本字符串。我也发现用这种方式构造ggplot代码可以更容易地重新排列,修改和调试。