2

我编写了以下代码来加热美国各州的热图。但我无法在 Google Colab 中获取输出图像。

州代码是美国特定州的两个字母代码。

temp = pd.DataFrame(project_data.groupby("school_state")["project_is_approved"].apply(np.mean)).reset_index()

temp.columns = ['state_code', 'num_proposals']

scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
            [0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]

data = [ dict(
        type='choropleth',
        colorscale = scl,
        autocolorscale = False,
        locations = temp['state_code'],
        z = temp['num_proposals'].astype(float),
        locationmode = 'USA-states',
        text = temp['state_code'],
        marker = dict(line = dict (color = 'rgb(255,255,255)',width = 2)),
        colorbar = dict(title = "% of pro")
    ) ]

layout = dict(
        title = 'Project Proposals % of Acceptance Rate by US States',
        geo = dict(
            scope='usa',
            projection=dict( type='albers usa' ),
            showlakes = True,
            lakecolor = 'rgb(255, 255, 255)',
        ),
    )

fig = dict(data=data, layout=layout)

offline.iplot(fig, filename='us-map-heat-map')

我已经导入了以下库:

from chart_studio import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
import chart_studio.plotly as py
4

1 回答 1

3

使用您的数据尝试以下代码:(
我尝试将您的变量放在正确的位置)

choropleth = go.Choropleth(
    locations=temp['state_code'],
    locationmode='USA-states',
    z = temp['num_proposals'].astype(float),
    zmin = 0,
    zmax = max(temp['num_proposals'].astype(float)),
    colorscale=scl,
    autocolorscale=False,
    text='Proposals', 
    marker_line_color='white',
    colorbar_title="% Acceptance Rate"
)
fig = go.Figure(data=choropleth)

fig.update_layout(
    title_text='Project Proposals % of Acceptance Rate by US States',
    geo = dict(
        scope='usa',
        projection=go.layout.geo.Projection(type = 'albers usa'),
        showlakes=True,
        lakecolor='rgb(255, 255, 255)'),
)

fig.show()

此代码的工作原理是使用您的数据创建 Plotly Choropleth 图形对象,然后将该对象加载到 Plotly 图图形对象中,然后更新布局(以获得正确的标题和缩放),最后显示图形。

于 2020-08-18T20:27:02.847 回答