我正在尝试绘制线图,其中颜色根据不同变量的值而变化(例如,y> 3使其变为红色,否则为绿色)。但是,当线条大小大于1时,构成线条的各个线段变得非常明显,而线条的单一颜色则不然。当绘制例如,这尤其成为一个问题。几年的每日数据,这是我在真实数据集中的数据。这是一个可重复的例子:
es_sub <- structure(list(date = structure(c(15323, 15324, 15327, 15328,
15329, 15330, 15331, 15334, 15335, 15336, 15337, 15338, 15341,
15342, 15343, 15344, 15345, 15348, 15349, 15350, 15351, 15352,
15355, 15356, 15357, 15358, 15359, 15362, 15363, 15364, 15365,
15366, 15369, 15370, 15371, 15372, 15373, 15376, 15377, 15378,
15379, 15380, 15383, 15384, 15385, 15386, 15387, 15390, 15391,
15392, 15393), class = "Date"), yield = c(4.3923, 4.2818, 4.22,
4.15263, 4.07348, 3.97288, 3.86626, 3.77447, 3.71084, 3.63926,
3.59491, 3.58036, 3.57425, 3.57158, 3.56352, 3.56215, 3.57652,
3.57602, 3.56521, 3.541, 3.50181, 3.47117, 3.43809, 3.39826,
3.35215, 3.3009, 3.23324, 3.16079, 3.09816, 3.05649, 3.00415,
2.93571, 2.87404, 2.81528, 2.7418, 2.65998, 2.57848, 2.51727,
2.46631, 2.43695, 2.43333, 2.45101, 2.46015, 2.47799, 2.51173,
2.54209, 2.56716, 2.59079, 2.60407, 2.60738, 2.60619), col = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L), .Label = c("2", "3"), class = "factor")), .Names = c("date",
"yield", "col"), row.names = 500:550, class = "data.frame")
ggplot(aes(x=date, y=yield, group=1), data=es_sub) +
geom_line(aes(color=ifelse(es_sub$yield>3,"red","green")), size=3) +
theme(legend.position="none")
ggplot(aes(x=date, y=yield, group=1), data=es_sub) + geom_line(size=3)
第一张图中的各个部分很明显,但第二部分则不然。有没有解决的办法?
更新:我尝试了Joran所建议的(即以与颜色相同的方式映射组),但这导致了这个问题(见图表)(这是我的真实情节。它有大约1000个观察,我没有我想把它们全部放在可重复的例子中。)
[1]: http://i.stack.imgur.com/38KPB.png
答案 0 :(得分:1)
试试这个:
ggplot(aes(x=date, y=yield, group=1), data=es_sub) +
geom_line(aes(color=ifelse(yield>3,"red","green"),
group = ifelse(yield>3,"red","green")), size=3) +
theme(legend.position="none")
(注意我没有使用$
来引用yield变量!不要这样做!)
答案 1 :(得分:1)
这是一个bodge而不是一个修复,但它确实改善了情节。添加 lineend = "圆形" 到 geom_line。
ggplot(aes(x = date, y = yield, group = 1), data = es_sub) +
geom_line(aes(color = ifelse(es_sub$yield > 3, "red", "green")), size = 3, lineend = "round" ) +
theme(legend.position = "none")