gpt4 book ai didi

r - 在R中,使用具有不同大小和颜色参数的geom_path

转载 作者:行者123 更新时间:2023-12-02 20:49:38 26 4
gpt4 key购买 nike

我真的很纠结ggplot2中geom_path的大小和颜色参数。让我首先与您分享我的数据和代码(都很短),然后展示我得到的图,然后解释我想要获得什么图。我现在对这个输出真的很困惑:

# the data - x and y coordinates to plot
x_loc = c(39.29376, 39.44371, 39.59578, 39.7439, 39.88808, 40.18122,
40.92207, 41.91831, 42.09564, 42.27909, 81.77751, 81.79779, 81.81031,
81.81723, 81.81997, 81.81846)

y_loc = c(21.02953, 20.91538, 20.80633, 20.69479, 20.58158, 20.37095,
19.87498, 19.38372, 19.31743, 19.26005, 35.55103, 35.64354, 35.7384,
35.82535, 35.9067, 35.98656)

# creating the factor with which to base size and color off of
end = length(x_loc)
distances = sqrt(((x_loc[2:end] - x_loc[1:(end-1)]) ^ 2) + ((y_loc[2:end] - y_loc[1:(end-1)]) ^ 2))
my_colors = c('black', ifelse(distances > 0.5, 'red', 'black'))

# and now for my plot
ggplot() +
geom_point(aes(x = x_loc, y = y_loc)) +
geom_path(aes(x = x_loc, y = y_loc, col = as.factor(my_colors), size = as.factor(my_colors)),
alpha = 1) +
scale_color_manual(values = c("black", "red")) +
scale_size_manual(values = c(1.5, 0.45))

如果您还没有运行我的代码,这是我得到的输出图:

enter image description here

这是我得到的,但这不是我想要的。我的目标是用连接点的线绘制坐标点,因此我对 geom_point() 和 geom_path() 使用单独的图层。但是,对于在距离向量中测量的很长的线(连续坐标之间的距离很长),我希望线条颜色为红色并且线条很细。对于短距离,我希望线条颜色为黑色并且线条更粗。

我上面的情节的问题是,长黑线不应该在那里。还有一条不应出现的附加黑线绘图(另一条红线所在的位置)。

(看来,通过将坐标分成组(按大小和颜色分组,均使用 my_colors 向量设置),geom_path 为两个独立的点组创建两个单独的路径,每个组都有各自的大小并且颜色正确。但是,这会导致错误的绘图)

如果我的解释不正确,请告诉我。我真的很想以某种方式弄清楚这件事的真相。我现在将手动创建一个与我想要的类似的绘图,并将很快对其进行编辑!

谢谢!

编辑:这是我希望得到的:

enter image description here

这是通过作弊创建的(作弊是指我可以在 16 个坐标上逃脱,但不能在 100K 上逃脱),使用以下 5 个 geom_path 层:

 ggplot() + geom_point(aes(x = x_loc, y = y_loc)) + 
geom_path(aes(x = x_loc[1:6], y = y_loc[1:6]),
color = 'black',
size = 1.5,
alpha = 1) +
geom_path(aes(x = x_loc[6:8], y = y_loc[6:8]),
color = 'red',
size = 0.45,
alpha = 1) +
geom_path(aes(x = x_loc[8:10], y = y_loc[8:10]),
color = 'black',
size = 1.5,
alpha = 1) +
geom_path(aes(x = x_loc[10:11], y = y_loc[10:11]),
color = 'red',
size = 0.45,
alpha = 1) +
geom_path(aes(x = x_loc[11:16], y = y_loc[11:16]),
color = 'black',
size = 1.5,
alpha = 1)

最佳答案

我想我自己解决了这个问题 - 对于任何从事此工作的人来说,都与分组有关。我很快就会用解决方案编辑它!

编辑:

ggplot() + 

geom_point(aes(x = x_loc, y = y_loc)) +
geom_path(aes(x = x_loc, y = y_loc, col = my_colors, size = my_colors, group = my_group),
alpha = 1) +
scale_color_manual(values = c("black", "red")) +
scale_size_manual(values = c(1.5, 0.45))

这样就完成了工作!,在分割颜色和尺寸之前需要将所有内容分组到同一组中

关于r - 在R中,使用具有不同大小和颜色参数的geom_path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com