为线图的特定段选择颜色的优雅方法? [英] Elegant way to select the color for a particular segment of a line plot?
问题描述
对于 n 对坐标 x,y 的列表,有没有办法在特定颜色上绘制不同点之间的线?
For a list of n pairs of coordinates x,y is there a way of plotting the line between different points on a specific color?
到目前为止我实现的解决方案不是使用 plot 函数,而是 lines 选择我想要颜色的范围.举个例子:
The solution I've implemented so far is not to use the plot function but lines selecting the range for which I want the color. Here an example:
x <- 1:100
y <- rnorm(100,1,100)
plot(x,y ,type='n')
lines(x[1:50],y[1:50], col='red')
lines(x[50:60],y[50:60], col='black')
lines(x[60:100],y[60:100], col='red')
有没有更简单的方法来做到这一点?
Is there an easier way of doing this?
推荐答案
是的,一种方法是使用 ggplot
.
Yes, one way of doing this is to use ggplot
.
ggplot
要求您的数据采用 data.frame
格式.在这个 data.frame
中,我添加了一列 col
来指示您想要的颜色.然后使用 ggplot
、geom_line
和 scale_colour_identity
构建图,因为 col 变量已经是一种颜色:
ggplot
requires your data to be in data.frame
format. In this data.frame
I add a column col
that indicates your desired colour. The plot is then constructed with ggplot
, geom_line
, and scale_colour_identity
since the col variable is already a colour:
library(ggplot2)
df <- data.frame(
x = 1:100,
y = rnorm(100,1,100),
col = c(rep("red", 50), rep("black", 10), rep("red", 40))
)
ggplot(df, aes(x=x, y=y)) +
geom_line(aes(colour=col, group=1)) +
scale_colour_identity()
更一般地,每个线段可以是不同的颜色.在下一个示例中,我将颜色映射到 x 值,给出了一个从蓝色平滑地将颜色变为红色的图:
More generally, each line segment can be a different colour. In the next example I map colour to the x value, giving a plot that smoothly changes colour from blue to red:
df <- data.frame(
x = 1:100,
y = rnorm(100,1,100)
)
ggplot(df, aes(x=x, y=y)) + geom_line(aes(colour=x))
如果你坚持使用基础图形,那么使用 segments
如下:
And if you insist on using base graphics, then use segments
as follows:
df <- data.frame(
x = 1:100,
y = rnorm(100,1,100),
col = c(rep("red", 50), rep("black", 10), rep("red", 40))
)
plot(df$x, df$y, type="n")
for(i in 1:(length(df$x)-1)){
segments(df$x[i], df$y[i], df$x[i+1], df$y[i+1], col=df$col[i])
}
这篇关于为线图的特定段选择颜色的优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!