簡體   English   中英

如何在 R 中繪制帶大小的顏色線

[英]How to draw color line with size in R

我有一個包含 700 多個觀察值的數據,但下面是一個示例。 使用 geom_curve 我想制作一個 plot,其中線條大小(total_trips)對應於一種顏色,例如 3 種不同的 colors。例如 0-100(total_trips)之間可以有紅色

df <- data.frame(
 origin_x = c(659627.8,642136.2,648774.7,659627.8,659627.8,658455.7,659627.8,659620.6,661641.8,656246.4),
 origin_y = c(6473200,6473200,6462166,6473200,6473200,6467413,6473200,6467163,6479577,6487039),
 dest_x = c(642136.2,659627.8,659627.8,648774.7,659620.6,659627.8,658455.7,659627.8,659627.8,659627.8),
 dest_y = c(6456563,6473200,6473200,6462166,6467163,6473200,6467413,6473200,6473200,6473200
),
 total_trips = c(4002,49878,2011,500,100,3000,2500,654,900,600))

我試過了

ggplot() + geom_sf(data=shapefile, colour='grey', fill='grey93', size = 0.25) + 
    geom_curve(
        data = df), 
        aes(
            x = origin_x,
            xend = dest_x,
            y = origin_y,
            yend = dest_y,
             size = n,
            colour= as.factor(c('red','blue'))),
        curvature = 0.3
    )  + scale_alpha_continuous(range = c(0.09,1)) +
    theme(
        axis.title = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        plot.title = element_text(hjust = 0.5, size = 6),
        plot.caption = element_text(hjust = 1),
        plot.caption.position = 'plot',
        axis.ticks = element_blank(),
        panel.background = element_rect(fill = 'white'),
        panel.grid = element_blank(),
        plot.background = element_rect(color = NA, size = 0.5, fill=NA),
        panel.border = element_rect(color = 'black', fill = NA, size=0.2) ,
        legend.position = c(0.89,0.15),
        legend.key.size = unit(0.4, 'cm'), 
        legend.text = element_text(size=7)  
    ) +
    annotation_scale(location = 'br', style = 'ticks') + coord_sf(crs=3301) +
    annotation_north_arrow(location = 'tr', width = unit(0.20, 'cm'),height = unit(0.5,'cm')) 

如果我理解正確——您想根據分類的連續變量 ( total_trips ) 更改線條的顏色,我們可以這樣做:

  1. 使用cut對變量進行分類並為組提供標簽
  2. 將這個新變量添加到aes(colour = .
library(dplyr)
library(ggplot2)

df <- df |> mutate(trips = cut(total_trips, c(0, 2000, 5000, 50000),
                               labels = c("0-2k", "2k-5k", "5k-50k")))

ggplot() +
  geom_curve(data = df, aes(x = origin_x,
                            xend = dest_x,
                            y = origin_y,
                            yend = dest_y,
                            size = total_trips,
                            colour = trips
                            ))

Output: 圖形

不過,不確定這是否是您想要的——您的樣本數據集不包含您在size = n中提到的變量n ,並且您沒有向我們提供shapefile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM