【问题标题】:plotting US heat map with text用文本绘制美国热图
【发布时间】:2015-04-01 02:05:04
【问题描述】:

输入:

Percent.Turnout  US.State
70               CA
80               NM
76               RI

我有美国 50 个州的数据。此外,US.State 的州缩写与函数 state.abb 中的缩写一致

我想创建一张美国地图,其中每个州都印有 Percent.Turnout。此外,使用 ColorBrewer 包,我想根据 Percent.Turnout 相对于其他状态为每个状态着色。

我对 ggplot 语法不是很熟悉,因此我们将不胜感激使用 base R 的建议(如果可行的话)

【问题讨论】:

    标签: r plot maps


    【解决方案1】:

    如果您想使用ggplot2,那么您需要做的主要事情是将州缩写列映射到小写的完整州名(为此,您可以使用state.name,但要一定要在其上应用tolower() 以获得正确的格式)。

    从那里,只需将您的数据集连接到该州的地理空间信息并绘制数据即可。以下代码段将带您逐步完成:

    # First, we need the ggplot2 library:
    > library(ggplot2)
    # We load the geospatial data for the states
    # (there are more options to the map_data function, 
    # if you are intrested in taking a look).
    > states <- map_data("state")
    # Here I'm creating a sample dataset like yours. 
    # The dataset will have 2 columns: The region (or state)
    # and a number that will represent the value that you
    # want to plot (here the value is just the numerical order of the states).
    > sim_data <- data.frame(region=unique(states$region), Percent.Turnout=match(unique(states$region), unique(states$region)))
    # Then we merge our dataset with the geospatial data:
    > sim_data_geo <- merge(states, sim_data, by="region")
    # The following should give us the plot without the numbers: 
    > qplot(long, lat, data=sim_data_geo, geom="polygon", fill=Percent.Turnout, group=group)
    

    这是上面这段代码的输出:

    现在,您说您还想将值 Percent.Turnout 添加到地图中。在这里,我们需要找到各种状态的中心点。您可以根据我们在上面检索到的地理空间数据(在states 数据框中)进行计算,但结果看起来不会很令人印象深刻。幸运的是,R 已经为我们计算了状态中心的值,我们可以利用它,如下所示:

    # We'll use the state.center list to tell us where exactly
    # the center of the state is.
    > snames <- data.frame(region=tolower(state.name), long=state.center$x, lat=state.center$y)
    # Then again, we need to join our original dataset 
    # to get the value that should be printed at the center.
    > snames <- merge(snames, sim_data, by="region")
    # And finally, to put everything together: 
    > ggplot(sim_data_geo, aes(long, lat)) + geom_polygon(aes(group=group, fill=Percent.Turnout)) + geom_text(data=snames, aes(long, lat, label=Percent.Turnout))
    

    这是上面最后一条语句的输出:

    【讨论】:

    • 精彩的答案!我遇到的一个小问题是,加利福尼亚州和科罗拉多州以及其他一些州内有一些空白区域。你知道为什么会这样吗?
    • 你能把你看到的截图显示一下吗?您描述的间隙是否与此图像中的任何区域相匹配 (thisisthegreenroom.com/wordpress/wp-content/uploads/2009/11/…)?如果是,那么states 数据集可能由于某种原因缺少某些子区域。
    • 我添加了一个屏幕截图作为我的问题的编辑。有两个相当大的差距很突出。
    • 您确定您在qplotgeom_polygon 中指定了group 参数吗?如果您未指定 group 参数,则地图将具有与您所看到的相似的间隙。如果您确实指定了 group 参数,那么我需要查看您用于生成绘图的代码段,以便了解发生这种情况的原因。了解您正在使用的 R 和 ggplot2 的版本也很有帮助。加载 ggplot2 库后,您可以运行命令 sessionInfo() 来获取它。我的是:R version 3.1.2 maps_2.3-9 ggplot2_1.0.0.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多