在散点图上绘制多个变量

问题描述 投票:1回答:1

我创建了一个看起来像这样的数据集:

> Data
   ZIP.Code Graduation.Rate  Residences  Tax_Payers   Businesses   Pot_Holes
1     60605      0.00876233 -0.43780716 -0.69756117 -0.705236816 -0.44078331
2     60607     -0.93779113 -0.62411552  0.45619155  0.429939383 -0.82886125
3     60608     -0.35352395  0.77774127  0.83458530  0.694500368  0.28789804
...

这些特征中的每一个的值都在[-1,1]范围内缩放。我希望有一个散点图,使得x轴具有ZIP_Code的标签,y轴对于每个缩放值具有4个标记。我怎么能在R中这样做?

r plot scatter-plot
1个回答
1
投票

将数据融合为长形式,以便将所有四个变量的数据传递给一个美学:

df_melt <- reshape2::melt(df, id.var = 'ZIP.Code')

# or
df_melt <- tidyr::gather(df, variable, value, Graduation.Rate:Pot_Holes)

df_melt
#    ZIP.Code        variable       value
# 1     60605 Graduation.Rate  0.00876233
# 2     60607 Graduation.Rate -0.93779113
# 3     60608 Graduation.Rate -0.35352395
# 4     60605      Residences -0.43780716
# 5     60607      Residences -0.62411552
# 6     60608      Residences  0.77774127
# 7     60605      Tax_Payers -0.69756117
# 8     60607      Tax_Payers  0.45619155
# 9     60608      Tax_Payers  0.83458530
# 10    60605      Businesses -0.70523682
# 11    60607      Businesses  0.42993938
# 12    60608      Businesses  0.69450037
# 13    60605       Pot_Holes -0.44078331
# 14    60607       Pot_Holes -0.82886125
# 15    60608       Pot_Holes  0.28789804

To plot with ggplot2

ggplot(df_melt, aes(x = factor(ZIP.Code), y = value, colour = variable)) + 
    geom_point() + xlab('ZIP Code')

ggplot


To plot with base

with(df_melt, plot(ZIP.Code, value, col = variable, pch = 19))

Base plot

请注意,它有一些问题,包括排列相当差的x轴。如果您真的附加到基本图形,按摩代码可以修复它们。

© www.soinside.com 2019 - 2024. All rights reserved.