r - ggplot2按形状分隔图例
问题描述
# Data:
zz <- "Small Large Lat Long
1 51 2 11 10
2 49 0 12 11
3 77 7 13 13
4 46 5 12 15
5 32 6 13 14
6 54 3 15 17
7 68 0 14 10
8 39 5 12 13"
Data <- as.data.frame(read.table(text=zz, header = TRUE))
我有一个连续变量,一个比率(小/大),我正在成功绘制。
虽然,“大”变量中存在一些 0。发生这种情况时,我只想绘制“小”数字,因为比率是不可能的。为此,我有以下内容:
ratio.both <- Data %>%
filter(Large > 0) %>%
mutate(Ratio = Small/Large)
only.sml<- Data %>%
filter(Large < 1)
然后我将两者都绘制在同一张图上(按经纬度数据):
ggplot() +
geom_point(data = ratio.both,
aes(x = Long,
y = Lat,
size = Ratio),
stroke = 0,
colour = '#3B3B3B',
shape=16) +
#
geom_point(data = only.sml,
aes(x = Long,
y = Lat,
size = Small,
shape=1),
stroke = 1,
shape=1)
注意形状的不同。这绘制了以下内容
那些是比率(填充)和那些只是小值之间的区别在地图上很清楚,但在图例中很难。
我想要传说中的以下内容:
#Title
Size = both.ratio$Ratio,
Shape/fill = Ratio or small value #whichever is easier
解决方案
使用内置的美学映射在表格中使用变量来对比数据要容易得多,而不是为小数据和大数据创建单独的几何图形。例如,您可以创建一个新变量来检查该数据点是属于大“类型”还是属于小“类型”。然后,您可以在美学中映射形状、颜色、大小或任何您想要的东西,并可选择手动为这些添加比例(如果需要)。
Data %>%
mutate(is_large = ifelse(Large > 0, "Ratio", "Small"),
size = ifelse(is_large == "Large", Small/Large, Small)) %>%
ggplot(aes(Long, Lat,
size = size,
shape = is_large)) +
geom_point() +
scale_shape_manual(values = c("Ratio" = 16, "Small" = 1),
name = "Size") +
scale_size_continuous(name = "Ratio/small value")
或者,如果您想按点颜色进行对比:
Data %>%
mutate(is_large = ifelse(Large > 0, "Ratio", "Small"),
size = ifelse(is_large == "Large", Small/Large, Small)) %>%
ggplot(aes(Long, Lat,
size = size,
color = is_large)) +
geom_point() +
scale_color_manual(values = c("Ratio" = "blue", "Small" = "red"),
name = "Size") +
scale_size_continuous(name = "Ratio/small value")
推荐阅读
- ssh - SSH+FreeIPA:从没有主目录的用户执行命令?
- javascript - 如何在javascript中全局覆盖html表单上的提交
- python - 无法在 OpenCV 上进行颜色检测(Python)
- ios - 如何解决 Stripe 支付网关中“您的卡被拒绝”的问题。迅速
- pandas - 根据不同其他列的标准在熊猫数据框中创建新列
- csv - 获取 pyarrow.lib.ArrowInvalid:CSV 解析错误:预期 9 列,得到 1
- installation - 如何在 Windows 10 上安装和运行 Neo4j?
- java - Spring Boot 自动装配属性问题
- matlab - MATLAB 中的机器人动画
- vue.js - 如何在 Vuejs 中加载 Pixijs BitmapText