Python 中 Plotly Express 的等值线图可以接受 CSS 格式的颜色吗?
Can choropleth graph of Plotly Express in Python accept colors in CSS format?
我正在 Python 中的 Plotly Express 上制作等值线图,以映射政府对 COVID-19 的回应;特别是在非洲。
可以找到数据源here。
它是牛津大学关于政府响应追踪器的数据集。
示例数据源内容(为了方便):
CountryName|CountryCode|Date |...|EconomicSupportIndexForDisplay
Algeria | DZA |20200101 |...| 0
Algeria | DZA |20200102 |...| 0
.........................................
Algeria | DZA |20200724 |...| 50
.........................................
实际上有42列3万多行;这些行每天更新。
但是,并非所有国家/地区都与时俱进(来源牛津 GitHub page)
就我而言,我已经在 PostgreSQL 中从中构建了一个数据库。
到目前为止,这是我的代码;
import psycopg2
import pandas as pd
import plotly.express as px
''' PostgreSQL Variables '''
# PostgreSQL Login Variables (edited out)
''' PostgreSQL Connection '''
# PostgreSQL DB Connection code (edited out)
African_Query = pd.read_sql_query(
'''
# SQL Query to pull all African countries from the DB (e.g. 'Algeria, 'Angola', 'Benin', 'etc')
''', conn)
# except ('Comoros', 'Equatorial Guinea', 'Guinea Bissau', and 'Sao Tome and Principe')
# those countries were not exist in the datasource
African = pd.DataFrame(African_Query,
columns=['all column names from the datasource'])
''' Plotly graph '''
# Government Respond - School Closing
african_figure1 = px.choropleth(African,
locations="countrycode",
color="c1_school_closing",
color_continuous_scale="Blues",
range_color=[0, 3],
hover_data={"c1_school_closing": False,
"countrycode": False,
"countryname": False},
hover_name="countryname",
labels={"c1_school_closing": "SCALE"})
african_figure1.update_layout(geo_scope='africa',
title_text="Government Respond - SCHOOL CLOSING")
african_figure1.show()
地图创建成功。现在我想做以下事情;
- 我想更改我使用的颜色。
从最初使用 Plotly 中的内置颜色选择器到 CSS 样式颜色之一。
例如进入 (#4c5c73)
*edit:我一直在尝试修改'color_continuous_scale="some_color_value"'
中的值,没有用。
还是我编辑错了?
非常感谢您的宝贵时间!
更改为基于 official reference 的 CSS 颜色格式。您所要做的就是以列表格式指定要使用的颜色。
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale=["#dc143c", "#ffd700", "#4169e1"],
range_color=(0, 12),
mapbox_style="carto-positron",
zoom=3, center = {"lat": 37.0902, "lon": -95.7129},
opacity=0.5,
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
对于碰到这个问题的任何人,
我找到了解决方法;感谢@r-beginners 提供的线索。
这就是我想要的;
my_color_scale = [[0.0, '#4c5c73'], [0.1, '#445267'], [0.2, '#3C495C'], [0.3, '#354050'],
[0.4, '#2D3745'], [0.5, '#262D39'], [0.6, '#1E242E'], [0.7, '#161B22'],
[0.8, '#0F1217'], [0.9, '#07090B'], [1.0, '#000000']]
我想要 shades/tints 的颜色列表,这基本上就是您需要在代码中添加的内容。
十六进制代码旁边的 0.0, 0.1, ...., 1.0
用于索引您的颜色及其阴影,因此稍后 Plotly 可以使用它。
如果你在plotly.express
中使用标准choropleth
(另一个是choropleth_mapbox
),你就是这样定义的。然后只需将带有您颜色的十六进制代码的变量输入 color_continouos_scale
;例如color_continuous_scale=my_color_scale
.
我是在重新阅读文档并向其他 space 的其他人询问有关此问题后发现的。
非常感谢您的宝贵时间!
编辑 1:有用的十六进制代码网站:https://color-hex.org/
编辑 2:完整代码
import psycopg2
import pandas as pd
import plotly.express as px
''' PostgreSQL Variables '''
# your postgres login variables
''' PostgreSQL Connection '''
# your postgres connection code
''' SQL Query '''
# your SQL Query
''' Load SQL Queries into Pandas DataFrame '''
African = pd.DataFrame(SQL_Query_Code,
columns=['list-of-all-columns'])
''' Variable for Personal Colours '''
# e.g. HTML/HEx code : '#4c5c73'
# List all of the shades/tints codes; in this example I am using the tints codes
my_color_scale = [[0.0, '#4c5c73'], [0.1, '#5D6C81'], [0.2, '#6F7C8F'], [0.3, '#818C9D'], [0.4, '#939DAB'],
[0.5, '#A5ADB9'], [0.6, '#B7BDC7'], [0.7, '#C9CED5'], [0.8, '#DBDEE3'], [0.9, '#EDEEF1'],
[1.0, '#FFFFFF']]
''' Plotly graph '''
# Government Respond - School Closing
african_figure1 = px.choropleth(African,
locations='countrycode',
color='c1_school_closing',
color_continuous_scale=my_color_scale,
range_color=[0, 3],
hover_data={'c1_school_closing': False,
'countrycode': False,
'countryname': False},
hover_name='countryname',
labels={'c1_school_closing': 'SCALE'})
african_figure1.update_layout(geo_scope='africa',
coloraxis_reversescale=True, # To reverse the order of color shades/tints
title_text='Government Respond - SCHOOL CLOSING <br> '
'Source: <a href="https://www.bsg.ox.ac.uk/research/research-projects'
'/coronavirus-government-response-tracker#data"> Oxford University '
'CORONAVIRUS '
'Government Respond Tracker</a>')
# african_figure1.show()
# african_figure1.write_html('file/path/file_name.html')
结果:
希望这有帮助。
我正在 Python 中的 Plotly Express 上制作等值线图,以映射政府对 COVID-19 的回应;特别是在非洲。
可以找到数据源here。
它是牛津大学关于政府响应追踪器的数据集。
示例数据源内容(为了方便):
CountryName|CountryCode|Date |...|EconomicSupportIndexForDisplay
Algeria | DZA |20200101 |...| 0
Algeria | DZA |20200102 |...| 0
.........................................
Algeria | DZA |20200724 |...| 50
.........................................
实际上有42列3万多行;这些行每天更新。
但是,并非所有国家/地区都与时俱进(来源牛津 GitHub page)
就我而言,我已经在 PostgreSQL 中从中构建了一个数据库。
到目前为止,这是我的代码;
import psycopg2
import pandas as pd
import plotly.express as px
''' PostgreSQL Variables '''
# PostgreSQL Login Variables (edited out)
''' PostgreSQL Connection '''
# PostgreSQL DB Connection code (edited out)
African_Query = pd.read_sql_query(
'''
# SQL Query to pull all African countries from the DB (e.g. 'Algeria, 'Angola', 'Benin', 'etc')
''', conn)
# except ('Comoros', 'Equatorial Guinea', 'Guinea Bissau', and 'Sao Tome and Principe')
# those countries were not exist in the datasource
African = pd.DataFrame(African_Query,
columns=['all column names from the datasource'])
''' Plotly graph '''
# Government Respond - School Closing
african_figure1 = px.choropleth(African,
locations="countrycode",
color="c1_school_closing",
color_continuous_scale="Blues",
range_color=[0, 3],
hover_data={"c1_school_closing": False,
"countrycode": False,
"countryname": False},
hover_name="countryname",
labels={"c1_school_closing": "SCALE"})
african_figure1.update_layout(geo_scope='africa',
title_text="Government Respond - SCHOOL CLOSING")
african_figure1.show()
地图创建成功。现在我想做以下事情;
- 我想更改我使用的颜色。 从最初使用 Plotly 中的内置颜色选择器到 CSS 样式颜色之一。 例如进入 (#4c5c73)
*edit:我一直在尝试修改'color_continuous_scale="some_color_value"'
中的值,没有用。
还是我编辑错了?
非常感谢您的宝贵时间!
更改为基于 official reference 的 CSS 颜色格式。您所要做的就是以列表格式指定要使用的颜色。
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale=["#dc143c", "#ffd700", "#4169e1"],
range_color=(0, 12),
mapbox_style="carto-positron",
zoom=3, center = {"lat": 37.0902, "lon": -95.7129},
opacity=0.5,
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
对于碰到这个问题的任何人,
我找到了解决方法;感谢@r-beginners 提供的线索。 这就是我想要的;
my_color_scale = [[0.0, '#4c5c73'], [0.1, '#445267'], [0.2, '#3C495C'], [0.3, '#354050'],
[0.4, '#2D3745'], [0.5, '#262D39'], [0.6, '#1E242E'], [0.7, '#161B22'],
[0.8, '#0F1217'], [0.9, '#07090B'], [1.0, '#000000']]
我想要 shades/tints 的颜色列表,这基本上就是您需要在代码中添加的内容。
十六进制代码旁边的 0.0, 0.1, ...., 1.0
用于索引您的颜色及其阴影,因此稍后 Plotly 可以使用它。
如果你在plotly.express
中使用标准choropleth
(另一个是choropleth_mapbox
),你就是这样定义的。然后只需将带有您颜色的十六进制代码的变量输入 color_continouos_scale
;例如color_continuous_scale=my_color_scale
.
我是在重新阅读文档并向其他 space 的其他人询问有关此问题后发现的。
非常感谢您的宝贵时间!
编辑 1:有用的十六进制代码网站:https://color-hex.org/
编辑 2:完整代码
import psycopg2
import pandas as pd
import plotly.express as px
''' PostgreSQL Variables '''
# your postgres login variables
''' PostgreSQL Connection '''
# your postgres connection code
''' SQL Query '''
# your SQL Query
''' Load SQL Queries into Pandas DataFrame '''
African = pd.DataFrame(SQL_Query_Code,
columns=['list-of-all-columns'])
''' Variable for Personal Colours '''
# e.g. HTML/HEx code : '#4c5c73'
# List all of the shades/tints codes; in this example I am using the tints codes
my_color_scale = [[0.0, '#4c5c73'], [0.1, '#5D6C81'], [0.2, '#6F7C8F'], [0.3, '#818C9D'], [0.4, '#939DAB'],
[0.5, '#A5ADB9'], [0.6, '#B7BDC7'], [0.7, '#C9CED5'], [0.8, '#DBDEE3'], [0.9, '#EDEEF1'],
[1.0, '#FFFFFF']]
''' Plotly graph '''
# Government Respond - School Closing
african_figure1 = px.choropleth(African,
locations='countrycode',
color='c1_school_closing',
color_continuous_scale=my_color_scale,
range_color=[0, 3],
hover_data={'c1_school_closing': False,
'countrycode': False,
'countryname': False},
hover_name='countryname',
labels={'c1_school_closing': 'SCALE'})
african_figure1.update_layout(geo_scope='africa',
coloraxis_reversescale=True, # To reverse the order of color shades/tints
title_text='Government Respond - SCHOOL CLOSING <br> '
'Source: <a href="https://www.bsg.ox.ac.uk/research/research-projects'
'/coronavirus-government-response-tracker#data"> Oxford University '
'CORONAVIRUS '
'Government Respond Tracker</a>')
# african_figure1.show()
# african_figure1.write_html('file/path/file_name.html')
结果: