我第一次尝试使用 Plotly 制作世界人口地图。剧情还好,就是传说离剧情太远了
我想请教以下方面的建议:1)如何缩小剧情与图例之间的差距,以及 2)如何将图例放置在图下方。
以下是我正在执行的步骤:
import pandas as pd
import plotly.express as px
url = 'https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population'
dfs = pd.read_html(url)
df = df.iloc[:, 1:3]
df = df[df['Location'] != 'World']
fig = px.choropleth(df,
locations='Location',
locationmode='country names',
color='Population',
color_continuous_scale='Viridis_r',
range_color=(df['Population'].min(), df['Population'].max()),
labels={'Population': 'Population'},
scope='africa')
fig.update_geos(showcountries=True, countrycolor="darkgrey")
fig.update_layout(
title='Population by Country',
title_x=0.5,
geo=dict(showframe=False, showcoastlines=False, projection_type='equirectangular'),
coloraxis_colorbar=dict(
title='Population',
x=0, y=-0.1,
xanchor='left', yanchor='bottom',
len=0.6
)
)
fig.show()
提前致谢!
我尝试了现有答案中的方法,但这些方法不适用于我的案例。
要使颜色条水平,请将颜色条的方向设置为水平并设置所需的 x,y 位置。如果图形区域定义为“纸张”,则 xy 设置范围为 0 到 1。请参阅此处了解更多信息。
import pandas as pd
import plotly.express as px
import requests
url = 'https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population'
r = requests.get(url)
df_list = pd.read_html(r.text)
df = df_list[0]
df = df.iloc[1:, 1:3]
fig = px.choropleth(df,
locations='Location',
locationmode='country names',
color='Population',
color_continuous_scale='Viridis_r',
range_color=(df['Population'].min(), df['Population'].max()),
labels={'Population': 'Population'},
scope='africa')
fig.update_geos(showcountries=True, countrycolor="darkgrey")
fig.update_layout(
title='Population by Country',
title_x=0.5,
geo=dict(showframe=False, showcoastlines=False, projection_type='equirectangular'),
coloraxis_colorbar=dict(
title='Population',
x=0, y=-0.1,
xanchor='left', yanchor='bottom',
len=0.6
)
)
fig.update_coloraxes(colorbar={'orientation':'h', 'thickness':20, 'y': -0.3, 'x':0.5, 'xanchor': 'center'})
fig.show()