import plotly.io as pio
pio.renderers.default = "plotly_mimetype+notebook_connected"Plotly基础(折线散点柱状图)+地图1
借鉴于和鲸社区Plotly教程(https://www.heywhale.com/mw/project/5ed49ab6946a0e002cb60d76)以及一些对地图的探索
基础图表
散点图 与 折线图
plotly.graph_objects as go
import plotly.graph_objects as go
import numpy as np
t=np.linspace(0,10,100)
y=np.sin(t)
#散点
data=go.Scatter(x=t,y=y,mode='markers')
fig=go.Figure(data)
fig.update_layout(title='Sine Wave',
xaxis_title='Time',
yaxis_title='Amplitude',
template='ggplot2')
fig.show()
#折线
data=go.Scatter(x=t,y=y,mode='lines')
fig=go.Figure(data)
fig.update_layout(title='Sine Wave',
xaxis_title='Time',
yaxis_title='Amplitude',
template='ggplot2')
fig.show()plotly.express as px
import plotly.express as px
import numpy as np
t=np.linspace(0,10,100)
y=np.sin(t)
fig = px.scatter(x=t, y=y)
fig.update_layout(title='Sine Wave',
xaxis_title='Time',
yaxis_title='Amplitude',
template='ggplot2')
fig.show()px.scatter还支持pandas的DataFrame格式
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame,官方自带的数据,常作为教程使用
df.head() # 来看看数据长什么样子| sepal_length | sepal_width | petal_length | petal_width | species | species_id | |
|---|---|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa | 1 |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa | 1 |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa | 1 |
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa | 1 |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa | 1 |
fig=px.scatter(df,x="sepal_width",
y="sepal_length",
template="simple_white")
fig.show()template= 常见选项:
- “plotly” (默认): 深色背景网格线
- “plotly_white”: 纯白背景
- “plotly_dark”: 深色主题
- “ggplot2”: 模仿 R 语言 ggplot2 风格
- “seaborn”: 类似 Seaborn 的调色板
- “simple_white”: 极简白底无网格线
- “presentation”: 高对比度(适合演示)
fig=px.scatter(df,
x="sepal_width",
y="sepal_length",
template="ggplot2",
color="species",#根据物种染色
size="petal_length",#根据petal_width大小调整散点大
hover_data=['petal_width'] #浮动展示还没有用到的petal_width数据,让用户可以一次性看到每条数据的全部维度
)
fig.show()help(px.scatter)Help on function scatter in module plotly.express._chart_types:
scatter(data_frame=None, x=None, y=None, color=None, symbol=None, size=None, hover_name=None, hover_data=None, custom_data=None, text=None, facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, animation_frame=None, animation_group=None, category_orders=None, labels=None, orientation=None, color_discrete_sequence=None, color_discrete_map=None, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, symbol_sequence=None, symbol_map=None, opacity=None, size_max=None, marginal_x=None, marginal_y=None, trendline=None, trendline_options=None, trendline_color_override=None, trendline_scope='trace', log_x=False, log_y=False, range_x=None, range_y=None, render_mode='auto', title=None, template=None, width=None, height=None) -> plotly.graph_objs._figure.Figure
In a scatter plot, each row of `data_frame` is represented by a symbol
mark in 2D space.
Parameters
----------
data_frame: DataFrame or array-like or dict
This argument needs to be passed for column names (and not keyword
names) to be used. Array-like and dict are transformed internally to a
pandas DataFrame. Optional: if missing, a DataFrame gets constructed
under the hood using the other arguments.
x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the x axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the y axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
color: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign color to marks.
symbol: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign symbols to marks.
size: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign mark sizes.
hover_name: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in bold
in the hover tooltip.
hover_data: str, or list of str or int, or Series or array-like, or dict
Either a name or list of names of columns in `data_frame`, or pandas
Series, or array_like objects or a dict with column names as keys, with
values True (for default formatting) False (in order to remove this
column from hover information), or a formatting string, for example
':.3f' or '|%a' or list-like data to appear in the hover tooltip or
tuples with a bool or formatting string as first element, and list-like
data to appear in hover as second element Values from these columns
appear as extra data in the hover tooltip.
custom_data: str, or list of str or int, or Series or array-like
Either name or list of names of columns in `data_frame`, or pandas
Series, or array_like objects Values from these columns are extra data,
to be used in widgets or Dash callbacks for example. This data is not
user-visible but is included in events emitted by the figure (lasso
selection etc.)
text: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in the
figure as text labels.
facet_row: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the vertical direction.
facet_col: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the horizontal direction.
facet_col_wrap: int
Maximum number of facet columns. Wraps the column variable at this
width, so that the column facets span multiple rows. Ignored if 0, and
forced to 0 if `facet_row` or a `marginal` is set.
facet_row_spacing: float between 0 and 1
Spacing between facet rows, in paper units. Default is 0.03 or 0.07
when facet_col_wrap is used.
facet_col_spacing: float between 0 and 1
Spacing between facet columns, in paper units Default is 0.02.
error_x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars. If `error_x_minus` is `None`, error bars will
be symmetrical, otherwise `error_x` is used for the positive direction
only.
error_x_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars in the negative direction. Ignored if `error_x`
is `None`.
error_y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars. If `error_y_minus` is `None`, error bars will
be symmetrical, otherwise `error_y` is used for the positive direction
only.
error_y_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars in the negative direction. Ignored if `error_y`
is `None`.
animation_frame: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to animation frames.
animation_group: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
provide object-constancy across animation frames: rows with matching
`animation_group`s will be treated as if they describe the same object
in each frame.
category_orders: dict with str keys and list of str values (default `{}`)
By default, in Python 3.6+, the order of categorical values in axes,
legends and facets depends on the order in which these values are first
encountered in `data_frame` (and no order is guaranteed by default in
Python below 3.6). This parameter is used to force a specific ordering
of values per column. The keys of this dict should correspond to column
names, and the values should be lists of strings corresponding to the
specific display order desired.
labels: dict with str keys and str values (default `{}`)
By default, column names are used in the figure for axis titles, legend
entries and hovers. This parameter allows this to be overridden. The
keys of this dict should correspond to column names, and the values
should correspond to the desired label to be displayed.
orientation: str, one of `'h'` for horizontal or `'v'` for vertical.
(default `'v'` if `x` and `y` are provided and both continous or both
categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and
`y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is
provided)
color_discrete_sequence: list of str
Strings should define valid CSS-colors. When `color` is set and the
values in the corresponding column are not numeric, values in that
column are assigned colors by cycling through `color_discrete_sequence`
in the order described in `category_orders`, unless the value of
`color` is a key in `color_discrete_map`. Various useful color
sequences are available in the `plotly.express.colors` submodules,
specifically `plotly.express.colors.qualitative`.
color_discrete_map: dict with str keys and str values (default `{}`)
String values should define valid CSS-colors Used to override
`color_discrete_sequence` to assign a specific colors to marks
corresponding with specific values. Keys in `color_discrete_map` should
be values in the column denoted by `color`. Alternatively, if the
values of `color` are valid colors, the string `'identity'` may be
passed to cause them to be used directly.
color_continuous_scale: list of str
Strings should define valid CSS-colors This list is used to build a
continuous color scale when the column denoted by `color` contains
numeric data. Various useful color scales are available in the
`plotly.express.colors` submodules, specifically
`plotly.express.colors.sequential`, `plotly.express.colors.diverging`
and `plotly.express.colors.cyclical`.
range_color: list of two numbers
If provided, overrides auto-scaling on the continuous color scale.
color_continuous_midpoint: number (default `None`)
If set, computes the bounds of the continuous color scale to have the
desired midpoint. Setting this value is recommended when using
`plotly.express.colors.diverging` color scales as the inputs to
`color_continuous_scale`.
symbol_sequence: list of str
Strings should define valid plotly.js symbols. When `symbol` is set,
values in that column are assigned symbols by cycling through
`symbol_sequence` in the order described in `category_orders`, unless
the value of `symbol` is a key in `symbol_map`.
symbol_map: dict with str keys and str values (default `{}`)
String values should define plotly.js symbols Used to override
`symbol_sequence` to assign a specific symbols to marks corresponding
with specific values. Keys in `symbol_map` should be values in the
column denoted by `symbol`. Alternatively, if the values of `symbol`
are valid symbol names, the string `'identity'` may be passed to cause
them to be used directly.
opacity: float
Value between 0 and 1. Sets the opacity for markers.
size_max: int (default `20`)
Set the maximum mark size when using `size`.
marginal_x: str
One of `'rug'`, `'box'`, `'violin'`, or `'histogram'`. If set, a
horizontal subplot is drawn above the main plot, visualizing the
x-distribution.
marginal_y: str
One of `'rug'`, `'box'`, `'violin'`, or `'histogram'`. If set, a
vertical subplot is drawn to the right of the main plot, visualizing
the y-distribution.
trendline: str
One of `'ols'`, `'lowess'`, `'rolling'`, `'expanding'` or `'ewm'`. If
`'ols'`, an Ordinary Least Squares regression line will be drawn for
each discrete-color/symbol group. If `'lowess`', a Locally Weighted
Scatterplot Smoothing line will be drawn for each discrete-color/symbol
group. If `'rolling`', a Rolling (e.g. rolling average, rolling median)
line will be drawn for each discrete-color/symbol group. If
`'expanding`', an Expanding (e.g. expanding average, expanding sum)
line will be drawn for each discrete-color/symbol group. If `'ewm`', an
Exponentially Weighted Moment (e.g. exponentially-weighted moving
average) line will be drawn for each discrete-color/symbol group. See
the docstrings for the functions in
`plotly.express.trendline_functions` for more details on these
functions and how to configure them with the `trendline_options`
argument.
trendline_options: dict
Options passed as the first argument to the function from
`plotly.express.trendline_functions` named in the `trendline`
argument.
trendline_color_override: str
Valid CSS color. If provided, and if `trendline` is set, all trendlines
will be drawn in this color rather than in the same color as the traces
from which they draw their inputs.
trendline_scope: str (one of `'trace'` or `'overall'`, default `'trace'`)
If `'trace'`, then one trendline is drawn per trace (i.e. per color,
symbol, facet, animation frame etc) and if `'overall'` then one
trendline is computed for the entire dataset, and replicated across all
facets.
log_x: boolean (default `False`)
If `True`, the x-axis is log-scaled in cartesian coordinates.
log_y: boolean (default `False`)
If `True`, the y-axis is log-scaled in cartesian coordinates.
range_x: list of two numbers
If provided, overrides auto-scaling on the x-axis in cartesian
coordinates.
range_y: list of two numbers
If provided, overrides auto-scaling on the y-axis in cartesian
coordinates.
render_mode: str
One of `'auto'`, `'svg'` or `'webgl'`, default `'auto'` Controls the
browser API used to draw marks. `'svg'` is appropriate for figures of
less than 1000 data points, and will allow for fully-vectorized output.
`'webgl'` is likely necessary for acceptable performance above 1000
points but rasterizes part of the output. `'auto'` uses heuristics to
choose the mode.
title: str
The figure title.
template: str or dict or plotly.graph_objects.layout.Template instance
The figure template name (must be a key in plotly.io.templates) or
definition.
width: int (default `None`)
The figure width in pixels.
height: int (default `None`)
The figure height in pixels.
Returns
-------
plotly.graph_objects.Figure
柱状图
# 导入数据
import plotly.express as px
data = px.data.gapminder() # 导入自带的数据
data_canada = data[data['country'] == 'Canada'] # 筛选加拿大的数据
data_canada.head()| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
|---|---|---|---|---|---|---|---|---|
| 240 | Canada | Americas | 1952 | 68.75 | 14785584 | 11367.16112 | CAN | 124 |
| 241 | Canada | Americas | 1957 | 69.96 | 17010154 | 12489.95006 | CAN | 124 |
| 242 | Canada | Americas | 1962 | 71.30 | 18985849 | 13462.48555 | CAN | 124 |
| 243 | Canada | Americas | 1967 | 72.13 | 20819767 | 16076.58803 | CAN | 124 |
| 244 | Canada | Americas | 1972 | 72.88 | 22284500 | 18970.57086 | CAN | 124 |
fig=px.bar(data_canada,x='year',y='pop')
fig.show()美化柱状图
#命名的内置连续色标
#https://plotly.com/python/builtin-colorscales/
"""
aggrnyl agsunset blackbody bluered blues blugrn bluyl brwnyl
bugn bupu burg burgyl cividis darkmint electric emrld
gnbu greens greys hot inferno jet magenta magma
mint orrd oranges oryel peach pinkyl plasma plotly3
pubu pubugn purd purp purples purpor rainbow rdbu
rdpu redor reds sunset sunsetdark teal tealgrn turbo
viridis ylgn ylgnbu ylorbr ylorrd algae amp deep
dense gray haline ice matter solar speed tempo
thermal turbid armyrose brbg earth fall geyser prgn
piyg picnic portland puor rdgy rdylbu rdylgn spectral
tealrose temps tropic balance curl delta oxy edge
hsv icefire phase twilight mrybm mygbm
"""'\naggrnyl agsunset blackbody bluered blues blugrn bluyl brwnyl\nbugn bupu burg burgyl cividis darkmint electric emrld\ngnbu greens greys hot inferno jet magenta magma\nmint orrd oranges oryel peach pinkyl plasma plotly3\npubu pubugn purd purp purples purpor rainbow rdbu\nrdpu redor reds sunset sunsetdark teal tealgrn turbo\nviridis ylgn ylgnbu ylorbr ylorrd algae amp deep\ndense gray haline ice matter solar speed tempo\nthermal turbid armyrose brbg earth fall geyser prgn\npiyg picnic portland puor rdgy rdylbu rdylgn spectral\ntealrose temps tropic balance curl delta oxy edge\nhsv icefire phase twilight mrybm mygbm\n'
fig = px.bar(data_canada,
x='year',
y='pop',
hover_data=['lifeExp', 'gdpPercap'], # 鼠标点击时的浮动数据
color='lifeExp', # 用预期寿命涂色
labels={'pop':'population of Canada'}, # 修改变量名
height=400 # 修改图片尺寸
)
fig.update_layout(title = 'Population of Canada',
coloraxis=dict(
colorscale='oryel'#内置方案:'Viridis', 'Plasma', 'Rainbow', 'Jet' 等
)
) # 加入标题,这里第一遇到,请记笔记!!!
fig.show()help(px.bar)Help on function bar in module plotly.express._chart_types:
bar(data_frame=None, x=None, y=None, color=None, pattern_shape=None, facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None, hover_name=None, hover_data=None, custom_data=None, text=None, base=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, animation_frame=None, animation_group=None, category_orders=None, labels=None, color_discrete_sequence=None, color_discrete_map=None, color_continuous_scale=None, pattern_shape_sequence=None, pattern_shape_map=None, range_color=None, color_continuous_midpoint=None, opacity=None, orientation=None, barmode='relative', log_x=False, log_y=False, range_x=None, range_y=None, text_auto=False, title=None, template=None, width=None, height=None) -> plotly.graph_objs._figure.Figure
In a bar plot, each row of `data_frame` is represented as a rectangular
mark.
Parameters
----------
data_frame: DataFrame or array-like or dict
This argument needs to be passed for column names (and not keyword
names) to be used. Array-like and dict are transformed internally to a
pandas DataFrame. Optional: if missing, a DataFrame gets constructed
under the hood using the other arguments.
x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the x axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position marks along the y axis in cartesian coordinates. Either `x` or
`y` can optionally be a list of column references or array_likes, in
which case the data will be treated as if it were 'wide' rather than
'long'.
color: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign color to marks.
pattern_shape: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign pattern shapes to marks.
facet_row: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the vertical direction.
facet_col: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to facetted subplots in the horizontal direction.
facet_col_wrap: int
Maximum number of facet columns. Wraps the column variable at this
width, so that the column facets span multiple rows. Ignored if 0, and
forced to 0 if `facet_row` or a `marginal` is set.
facet_row_spacing: float between 0 and 1
Spacing between facet rows, in paper units. Default is 0.03 or 0.07
when facet_col_wrap is used.
facet_col_spacing: float between 0 and 1
Spacing between facet columns, in paper units Default is 0.02.
hover_name: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in bold
in the hover tooltip.
hover_data: str, or list of str or int, or Series or array-like, or dict
Either a name or list of names of columns in `data_frame`, or pandas
Series, or array_like objects or a dict with column names as keys, with
values True (for default formatting) False (in order to remove this
column from hover information), or a formatting string, for example
':.3f' or '|%a' or list-like data to appear in the hover tooltip or
tuples with a bool or formatting string as first element, and list-like
data to appear in hover as second element Values from these columns
appear as extra data in the hover tooltip.
custom_data: str, or list of str or int, or Series or array-like
Either name or list of names of columns in `data_frame`, or pandas
Series, or array_like objects Values from these columns are extra data,
to be used in widgets or Dash callbacks for example. This data is not
user-visible but is included in events emitted by the figure (lasso
selection etc.)
text: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like appear in the
figure as text labels.
base: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
position the base of the bar.
error_x: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars. If `error_x_minus` is `None`, error bars will
be symmetrical, otherwise `error_x` is used for the positive direction
only.
error_x_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size x-axis error bars in the negative direction. Ignored if `error_x`
is `None`.
error_y: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars. If `error_y_minus` is `None`, error bars will
be symmetrical, otherwise `error_y` is used for the positive direction
only.
error_y_minus: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
size y-axis error bars in the negative direction. Ignored if `error_y`
is `None`.
animation_frame: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
assign marks to animation frames.
animation_group: str or int or Series or array-like
Either a name of a column in `data_frame`, or a pandas Series or
array_like object. Values from this column or array_like are used to
provide object-constancy across animation frames: rows with matching
`animation_group`s will be treated as if they describe the same object
in each frame.
category_orders: dict with str keys and list of str values (default `{}`)
By default, in Python 3.6+, the order of categorical values in axes,
legends and facets depends on the order in which these values are first
encountered in `data_frame` (and no order is guaranteed by default in
Python below 3.6). This parameter is used to force a specific ordering
of values per column. The keys of this dict should correspond to column
names, and the values should be lists of strings corresponding to the
specific display order desired.
labels: dict with str keys and str values (default `{}`)
By default, column names are used in the figure for axis titles, legend
entries and hovers. This parameter allows this to be overridden. The
keys of this dict should correspond to column names, and the values
should correspond to the desired label to be displayed.
color_discrete_sequence: list of str
Strings should define valid CSS-colors. When `color` is set and the
values in the corresponding column are not numeric, values in that
column are assigned colors by cycling through `color_discrete_sequence`
in the order described in `category_orders`, unless the value of
`color` is a key in `color_discrete_map`. Various useful color
sequences are available in the `plotly.express.colors` submodules,
specifically `plotly.express.colors.qualitative`.
color_discrete_map: dict with str keys and str values (default `{}`)
String values should define valid CSS-colors Used to override
`color_discrete_sequence` to assign a specific colors to marks
corresponding with specific values. Keys in `color_discrete_map` should
be values in the column denoted by `color`. Alternatively, if the
values of `color` are valid colors, the string `'identity'` may be
passed to cause them to be used directly.
color_continuous_scale: list of str
Strings should define valid CSS-colors This list is used to build a
continuous color scale when the column denoted by `color` contains
numeric data. Various useful color scales are available in the
`plotly.express.colors` submodules, specifically
`plotly.express.colors.sequential`, `plotly.express.colors.diverging`
and `plotly.express.colors.cyclical`.
pattern_shape_sequence: list of str
Strings should define valid plotly.js patterns-shapes. When
`pattern_shape` is set, values in that column are assigned patterns-
shapes by cycling through `pattern_shape_sequence` in the order
described in `category_orders`, unless the value of `pattern_shape` is
a key in `pattern_shape_map`.
pattern_shape_map: dict with str keys and str values (default `{}`)
Strings values define plotly.js patterns-shapes. Used to override
`pattern_shape_sequences` to assign a specific patterns-shapes to lines
corresponding with specific values. Keys in `pattern_shape_map` should
be values in the column denoted by `pattern_shape`. Alternatively, if
the values of `pattern_shape` are valid patterns-shapes names, the
string `'identity'` may be passed to cause them to be used directly.
range_color: list of two numbers
If provided, overrides auto-scaling on the continuous color scale.
color_continuous_midpoint: number (default `None`)
If set, computes the bounds of the continuous color scale to have the
desired midpoint. Setting this value is recommended when using
`plotly.express.colors.diverging` color scales as the inputs to
`color_continuous_scale`.
opacity: float
Value between 0 and 1. Sets the opacity for markers.
orientation: str, one of `'h'` for horizontal or `'v'` for vertical.
(default `'v'` if `x` and `y` are provided and both continous or both
categorical, otherwise `'v'`(`'h'`) if `x`(`y`) is categorical and
`y`(`x`) is continuous, otherwise `'v'`(`'h'`) if only `x`(`y`) is
provided)
barmode: str (default `'relative'`)
One of `'group'`, `'overlay'` or `'relative'` In `'relative'` mode,
bars are stacked above zero for positive values and below zero for
negative values. In `'overlay'` mode, bars are drawn on top of one
another. In `'group'` mode, bars are placed beside each other.
log_x: boolean (default `False`)
If `True`, the x-axis is log-scaled in cartesian coordinates.
log_y: boolean (default `False`)
If `True`, the y-axis is log-scaled in cartesian coordinates.
range_x: list of two numbers
If provided, overrides auto-scaling on the x-axis in cartesian
coordinates.
range_y: list of two numbers
If provided, overrides auto-scaling on the y-axis in cartesian
coordinates.
text_auto: bool or string (default `False`)
If `True` or a string, the x or y or z values will be displayed as
text, depending on the orientation A string like `'.2f'` will be
interpreted as a `texttemplate` numeric formatting directive.
title: str
The figure title.
template: str or dict or plotly.graph_objects.layout.Template instance
The figure template name (must be a key in plotly.io.templates) or
definition.
width: int (default `None`)
The figure width in pixels.
height: int (default `None`)
The figure height in pixels.
Returns
-------
plotly.graph_objects.Figure
分组柱状图
import plotly.graph_objects as go
animals=['giraffes', 'orangutans', 'monkeys']
fig = go.Figure(data=[
go.Bar(name='SF Zoo', x=animals, y=[20, 14, 23]), # name是区分不同组的最主要参数
go.Bar(name='LA Zoo', x=animals, y=[12, 18, 29])
])
# Change the bar mode
fig.update_layout(barmode='group', # 设置分组方式,这里显示为并列
template='simple_white')
fig.show()堆积柱状图
import plotly.graph_objects as go
animals=['giraffes', 'orangutans', 'monkeys']
fig = go.Figure(data=[
go.Bar(name='SF Zoo', x=animals, y=[20, 14, 23]),
go.Bar(name='LA Zoo', x=animals, y=[12, 18, 29])]
)
# Change the bar mode
fig.update_layout(barmode='stack',
template='ggplot2') # 设置分组方式为堆积
fig.show()柱状图加标注
import plotly.graph_objects as go
x = ['Product A', 'Product B', 'Product C']
y = [20, 14, 23]
fig = go.Figure(data=[go.Bar(
x=x, y=y,
text=y,
textposition='auto', # 标注位置自动调整
)])
fig.show()
#---------------------------------------------
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
fig = px.bar(df,
y='pop',
x='country',
text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='inside')
#fig.update_traces()方法,该方法可用于调整柱状图文字的显示格式以及显示的位置。
fig.update_layout(uniformtext_minsize=2, uniformtext_mode='hide')
#uniformtext_minsize用以调整最小尺寸,uniformtext_mode用以调整不合规范的数字是隐藏还是显示。
# 添加折线图(显示预期寿命)
fig.add_trace(
# go.Scatter(
# x=df['country'],
# y=df['pop'],
# name='预期寿命',
# line=dict(color='red')
px.line(
x=df['country'],
y=df['pop'],
#红色线条
).data[0].update(
line=dict(color='red'),
)
)
# # 配置双轴布局
# fig.update_layout(
# title='欧洲国家人口与预期寿命(2007)',
# uniformtext_minsize=2,
# uniformtext_mode='hide',
# yaxis=dict(title='人口'),
# yaxis2=dict(
# title='预期寿命(年)',
# overlaying='y',
# side='right',
# range=[70, 85] # 优化显示范围
# ),
# legend=dict(x=1.1) # 防止图例遮挡
# )
fig.show()旋转坐标轴
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
fig = px.bar(df,
y='pop',
x='country',
text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside',
marker_color='rgb(0, 128, 0)', # 颜色
opacity=0.3, # 透明度
)
fig.update_layout(uniformtext_minsize=5, uniformtext_mode='show',
template='ggplot2'
)
fig.update_layout(xaxis_tickangle=-45) # 重点这一行,坐标轴旋转45度,方便阅读
fig.show()以下是 fig.update_traces 和 fig.update_layout 的核心区别及用途总结:
1. fig.update_traces
作用对象:修改图表中的 单个或多个迹(traces)(例如柱状图的柱子、折线图的线条、散点图的点等)。
核心用途:调整数据可视化的具体表现(颜色、文本、形状等)。
常用参数:
fig.update_traces( texttemplate='%{text:.2s}', # 文本格式 textposition='outside', # 文本位置 marker_color='blue', # 颜色 opacity=0.7, # 透明度 hoverinfo='text+value', # 悬停信息 line_width=2 # 线宽 )适用场景:
修改特定数据元素的样式(如柱状图的颜色、文本标签、悬停行为等)。
2. fig.update_layout
作用对象:调整图表的 整体布局(标题、坐标轴、图例、背景等)。
核心用途:控制图表的全局外观和结构。
常用参数:
fig.update_layout( title='标题', # 图表标题 xaxis_title='X轴', # X轴标签 yaxis_title='Y轴', # Y轴标签 uniformtext_minsize=8, # 统一文本最小尺寸 legend=dict(x=0.5, y=1.1), # 图例位置 margin=dict(l=50, r=50) # 边距 )适用场景:
调整全局布局(如标题、坐标轴范围、图例位置、背景颜色等)。
关键区别
| 特性 | update_traces |
update_layout |
|---|---|---|
| 作用对象 | 数据迹(单个/多个图形元素) | 图表整体布局 |
| 修改内容 | 数据元素的样式(颜色、文本等) | 布局结构(标题、坐标轴、边距等) |
| 示例用途 | 调整柱状图的颜色或文本标签 | 设置图表标题或调整图例位置 |
何时用哪个?
- 需要修改数据图形(如柱子的颜色、点的形状) →
update_traces
- 需要调整图表框架(如标题、坐标轴、背景) →
update_layout
例如:
# 修改迹的属性(柱状图颜色和文本)
fig.update_traces(marker_color='green', textposition='inside')
# 修改布局属性(添加标题和调整边距)
fig.update_layout(title='销售数据', margin=dict(l=100))横柱状图
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 9.e6")
fig = px.bar(df,
x='pop',
y='country',
orientation = 'h', # 设置横向柱形图的方法,注意这时候x和y要反向
height = 700,
text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=10, uniformtext_mode='hide')
fig.update_layout(xaxis_tickangle=-45,
)
fig.show()颜色自定义
import plotly.graph_objects as go
colors = ['lightslategray',]*5
print(colors)
colors[1] = 'crimson'
colors[2] = '#ffffff'
print(colors)
fig = go.Figure(data=[go.Bar(
x=['Feature A', 'Feature B', 'Feature C',
'Feature D', 'Feature E'],
y=[20, 14, 23, 25, 22],
marker_color=colors # 颜色可以使单个颜色(标量),或者和数据维度一致
)])
fig.update_layout(title_text='Least Used Feature')['lightslategray', 'lightslategray', 'lightslategray', 'lightslategray', 'lightslategray']
['lightslategray', 'crimson', '#ffffff', 'lightslategray', 'lightslategray']
宽度自定义
import plotly.graph_objects as go
fig = go.Figure(data=[go.Bar(
x=[1, 2, 3, 5.5, 10],
y=[10, 8, 6, 4, 2],
width=[0.8, 0.8, 0.8, 3.5, 4] # customize width here
)])
fig.show()起点自定义
import plotly.graph_objects as go
years = ['2016','2017','2018']
fig = go.Figure()
fig.add_trace(go.Bar(x=years, y=[500, 600 ,700],
base=[-500,-600,-700],
marker_color='crimson',
name='expenses'))
fig.add_trace(go.Bar(x=years, y=[300, 400, 700],
base=0,
marker_color='lightslategrey',
name='revenue'
))
fig.show()案例汇总
import plotly.graph_objects as go
# 给出数据
years = [1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012]
#初始化绘图
fig = go.Figure()
fig.add_trace(go.Bar(x=years,
y=[219, 146, 112, 127, 124, 180, 236, 207, 236, 263,
350, 430, 474, 526, 488, 537, 500, 439],
name='Rest of world',
marker_color='rgb(55, 83, 109)'
))
fig.add_trace(go.Bar(x=years,
y=[16, 13, 10, 11, 28, 37, 43, 55, 56, 88, 105, 156, 270,
299, 340, 403, 549, 499],
name='US',
marker_color='rgb(26, 118, 255)'
))
fig.update_layout(
title='US Export of Plastic Scrap',
xaxis_tickfont_size=14,
yaxis=dict(
title='USD (millions)',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
x=0,
y=1.0,
bgcolor='rgba(1, 255, 1, 0)',
bordercolor='rgba(0, 255, 255, 0)'
),
#barmode='group',
barmode='stack',
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1 # gap between bars of the same location coordinate.
)
fig.show()自定义柱状图展示顺序
import plotly.graph_objects as go
x=['b', 'a', 'c', 'd']
fig = go.Figure(go.Bar(x=x, y=[2,5,1,9], name='Montreal'))
fig.add_trace(go.Bar(x=x, y=[1, 4, 9, 16], name='Ottawa'))
fig.add_trace(go.Bar(x=x, y=[6, 8, 4.5, 8], name='Toronto'))
fig.update_layout(barmode='stack', xaxis={'categoryorder':'category ascending'}) # 字母表升序
fig.show()x=['b', 'a', 'c', 'd']
fig = go.Figure(go.Bar(x=x, y=[2,5,1,9], name='Montreal'))
fig.add_trace(go.Bar(x=x, y=[1, 4, 9, 16], name='Ottawa'))
fig.add_trace(go.Bar(x=x, y=[6, 8, 4.5, 8], name='Toronto'))
fig.update_layout(barmode='stack', xaxis={'categoryorder':'array', 'categoryarray':['d','a','c','b']})# 自定顺序
fig.show()import plotly.graph_objects as go
x=['b', 'a', 'c', 'd']
fig = go.Figure(go.Bar(x=x, y=[2,5,1,9], name='Montreal'))
fig.add_trace(go.Bar(x=x, y=[1, 4, 9, 16], name='Ottawa'))
fig.add_trace(go.Bar(x=x, y=[6, 8, 4.5, 8], name='Toronto'))
fig.update_layout(barmode='stack', xaxis={'categoryorder':'total descending'}) # 总数降序
fig.show()地图
https://www.zhihu.com/tardis/zm/art/372672532?source_id=1005
地理区块图
import plotly.express as px
df = px.data.gapminder()
df = df[df['year'] == 2007]
df.head()| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
|---|---|---|---|---|---|---|---|---|
| 11 | Afghanistan | Asia | 2007 | 43.828 | 31889923 | 974.580338 | AFG | 4 |
| 23 | Albania | Europe | 2007 | 76.423 | 3600523 | 5937.029526 | ALB | 8 |
| 35 | Algeria | Africa | 2007 | 72.301 | 33333216 | 6223.367465 | DZA | 12 |
| 47 | Angola | Africa | 2007 | 42.731 | 12420476 | 4797.231267 | AGO | 24 |
| 59 | Argentina | Americas | 2007 | 75.320 | 40301927 | 12779.379640 | ARG | 32 |
fig = px.choropleth(df,
#locations="iso_alpha", # 给出区块的id,这里用的是国际iso_alpha标准
locations="country",
locationmode="country names",
color="pop", # 设定人均寿命为颜色
hover_name="country", # 设定浮动信息展示国家名
color_continuous_scale=px.colors.sequential.YlGn, # 选用 colorbar
scope="asia",
# ['africa', 'asia', 'europe', 'north america', 'south
# america', 'usa', 'world']
)
fig.show()地理轨迹
import plotly.graph_objects as go
import pandas as pd
# 机场位置数据,用于画点
df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
#df_airports = pd.read_csv('/home/kesci/input/plotly_tutorial6322/2011_february_us_airport_traffic.csv')
# 航线数据,用于连线
df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
#df_flight_paths = pd.read_csv('/home/kesci/input/plotly_tutorial6322/2011_february_aa_flight_paths.csv')
# 初始化图层
fig = go.Figure()
# 画点
fig.add_trace(go.Scattergeo(
locationmode = 'USA-states',
lon = df_airports['long'],
lat = df_airports['lat'],
hoverinfo = 'text',
text = df_airports['airport'],
mode = 'markers',
marker = dict(
size = 2,
color = 'rgb(255, 0, 0)',
line = dict(
width = 3,
color = 'rgba(68, 68, 68, 0)'
)
)))
# 连线
flight_paths = []
for i in range(len(df_flight_paths)):
fig.add_trace(
go.Scattergeo(
locationmode = 'USA-states',
lon = [df_flight_paths['start_lon'][i], df_flight_paths['end_lon'][i]],
lat = [df_flight_paths['start_lat'][i], df_flight_paths['end_lat'][i]],
mode = 'lines',
line = dict(width = 1,color = 'red'),
opacity = float(df_flight_paths['cnt'][i]) / float(df_flight_paths['cnt'].max()),
)
)
# 设置标题,图例、地图格式
fig.update_layout(
title_text = 'Feb. 2011 American Airline flight paths<br>(Hover for airport names)',
showlegend = False,
geo = dict(
scope = 'north america',
projection_type = 'azimuthal equal area',
showland = True,
landcolor = 'rgb(243, 243, 243)',
countrycolor = 'rgb(204, 204, 204)',
),
)
fig.show()动态地图
import plotly.express as px
df = px.data.gapminder()
# df: 数据源,通常是一个Pandas DataFrame
# locations="iso_alpha": 使用ISO国家代码来标识地图上的位置
# color="continent": 根据大洲对点进行着色,以便不同大洲用不同颜色区分
# hover_name="country": 鼠标悬停时显示国家名称,增加交互性
# size="pop": 点的大小基于人口数量,以直观展示各国人口
# animation_frame="year": 以年份为动画帧,展示时间序列上的变化
# projection="natural earth": 使用“自然地球”投影方式来绘制地图,以平衡形状和面积的变形,适合展示全球数据
fig = px.scatter_geo(df, locations="iso_alpha", color="continent",
hover_name="country", size="pop",
animation_frame="year",
#projection="natural earth"
projection="natural earth"
)
# ['airy', 'aitoff', 'albers', 'albers usa', 'august',
# 'azimuthal equal area', 'azimuthal equidistant', 'baker',
# 'bertin1953', 'boggs', 'bonne', 'bottomley', 'bromley',
# 'collignon', 'conic conformal', 'conic equal area', 'conic
# equidistant', 'craig', 'craster', 'cylindrical equal
# area', 'cylindrical stereographic', 'eckert1', 'eckert2',
# 'eckert3', 'eckert4', 'eckert5', 'eckert6', 'eisenlohr',
# 'equal earth', 'equirectangular', 'fahey', 'foucaut',
# 'foucaut sinusoidal', 'ginzburg4', 'ginzburg5',
# 'ginzburg6', 'ginzburg8', 'ginzburg9', 'gnomonic',
# 'gringorten', 'gringorten quincuncial', 'guyou', 'hammer',
# 'hill', 'homolosine', 'hufnagel', 'hyperelliptical',
# 'kavrayskiy7', 'lagrange', 'larrivee', 'laskowski',
# 'loximuthal', 'mercator', 'miller', 'mollweide', 'mt flat
# polar parabolic', 'mt flat polar quartic', 'mt flat polar
# sinusoidal', 'natural earth', 'natural earth1', 'natural
# earth2', 'nell hammer', 'nicolosi', 'orthographic',
# 'patterson', 'peirce quincuncial', 'polyconic',
# 'rectangular polyconic', 'robinson', 'satellite', 'sinu
# mollweide', 'sinusoidal', 'stereographic', 'times',
# 'transverse mercator', 'van der grinten', 'van der
# grinten2', 'van der grinten3', 'van der grinten4',
# 'wagner4', 'wagner6', 'wiechel', 'winkel tripel',
# 'winkel3']
fig.show()https://blog.csdn.net/qq_52964132/article/details/145744278
高德地图
ESRI && Bing
URL: - ESRI Standard : https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x} - ESRI Satellite : https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}
REST :
https://sampleserver6.arcgisonline.com/arcgis/rest/services
https://sampleserver5.arcgisonline.com/arcgis/rest/services
open data
https://hub.arcgis.com/search
行政边界 https://hub.arcgis.com/datasets/cccd798cdd6443da9346be7185ffdcbc_0/explore?location=31.324383%2C-94.975842%2C6.16&showTable=true
import plotly.graph_objects as go
import numpy as np
import pandas as pd
sampledata = pd.DataFrame({'lat': 38 + np.random.rand(1000),
'lon': -78+np.random.rand(1000), })
basemap_layer = [
dict(
below="traces",
sourcetype="raster",
sourceattribution="ESRI",
source=[
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
]
)
]
mapbox_kargs = dict(
zoom=10, # 这里的zoom代表地图瓦片缩放的等级,可以依次+1、-1试一试
center=dict(
lat=38, # 这里是设置你的地图的中心点,经纬度要设置好
lon=-78,
),
style="white-bg",
layers=basemap_layer,
)
layout_kargs = dict(
autosize=True,
width=500, # 这里设置的是输出的图的宽度和长度。
height=300,
margin=dict(
r=0, t=38, l=0, b=0, pad=0
),
)
layout = go.Layout(
mapbox=mapbox_kargs,
**layout_kargs
)
fig = go.Figure(
data=go.Scattermapbox(lat=sampledata['lat'], # 这里依次传递经纬度给函数
lon=sampledata['lon'],
mode='markers',
),
layout=layout
)
fig.show()
#fig.write_html("file083101.html") # 将plotly保存为html文件,后续使用浏览器直接打开这个文件即可import requests
import plotly.graph_objects as go
# 1. 获取边界数据
url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/2/query"
params = {
'where': "NAME = 'Juneau'",
'outFields': '*',
'returnGeometry': 'true',
'f': 'geojson'
}
response = requests.get(url, params=params)
data = response.json()
# 2. 解析GeoJSON数据
if not data.get('features'):
raise ValueError("未找到Juneau的边界数据")
feature = data['features'][0]
geometry = feature['geometry']
coordinates = geometry['coordinates']
# 3. 坐标处理逻辑
lons, lats = [], []
if geometry['type'] == 'Polygon':
# 处理单个多边形
boundary = coordinates[0] # 取外边界
lons = [coord[0] for coord in boundary]
lats = [coord[1] for coord in boundary]
elif geometry['type'] == 'MultiPolygon':
# 处理多个多边形
for poly_idx, polygon in enumerate(coordinates):
# 每个子多边形的外边界
boundary = polygon[0]
# 添加坐标
lons.extend([coord[0] for coord in boundary])
lats.extend([coord[1] for coord in boundary])
# 用None分隔不同多边形(最后一个不添加)
if poly_idx < len(coordinates)-1:
lons.append(None)
lats.append(None)
else:
raise ValueError("不支持的几何类型:" + geometry['type'])
# 4. 创建地图可视化
fig = go.Figure(
# go.Scattermapbox(
# mode="lines",
# lon=lons,
# lat=lats,
# line={'width': 2, 'color': 'red'},
# name="Juneau Boundary",
# showlegend=True)
go.Scattermapbox(
mode="lines",
lon=lons,
lat=lats,
#line={'width': 1.5, 'color': 'darkred'},
line={'width': 1.5, 'color': 'yellow'},
fill='toself',
fillcolor='rgba(255,50,50,0.4)', # 可调参数:RGBA(红,绿,蓝,透明度)
opacity=0.7, # 整体透明度(可选)
hoverinfo="text",
hovertext="Juneau City Boundary" # 悬停提示
))
# 配置底图参数
fig.update_layout(
mapbox={
'style': "white-bg",
'layers': [{
'below': 'traces',
'sourcetype': "raster",
'source': [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
]
}],
'center': {'lon': sum(filter(None, lons))/len(list(filter(None, lons))),
'lat': sum(filter(None, lats))/len(list(filter(None, lats)))},
'zoom': 5
},
width=500,
height=300,
margin={"r":0,"t":0,"l":0,"b":0}
)
fig.show()import requests
import plotly.graph_objects as go
# 1. 获取边界数据
url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/2/query"
params = {
'where': "STATE_NAME = 'Alaska'",
'outFields': '*',
'returnGeometry': 'true',
'f': 'geojson'
}
response = requests.get(url, params=params)
data = response.json()
# 4. 创建地图可视化(使用Choroplethmapbox)
fig = go.Figure(go.Choroplethmapbox(
# geojson=data, # 直接使用原始几何数据
# locations=['Juneau'], # 对应feature的索引
# z=[1], # 颜色值(这里用固定值)
# colorscale=[[0, 'rgba(255,0,0,0.3)'], [1, 'rgba(255,0,0,0.3)']], # 固定半透明红色
# marker_opacity=0.3, # 整体透明度
# marker_line_width=1, # 边界线宽度
# marker_line_color='red', # 边界线颜色
# featureidkey="properties.NAME", # 关联属性字段
# showscale=False # 隐藏色标
geojson=data,
locations=[f['properties']['NAME'] for f in data['features']], # 县名列表
z=[1]*len(data['features']), # 统一颜色值
colorscale=[[0, 'rgba(0,100,0,0.3)'], [1, 'rgba(0,100,0,0.3)']],
marker_opacity=0.6,
marker_line_width=0.8,
marker_line_color='yellow',
featureidkey="properties.NAME",
showscale=False
))
fig.update_layout(
mapbox={
'style': "white-bg",
'layers': [{
'below': 'traces',
'sourcetype': "raster",
'source': [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
]
}],
'center': {'lon':-152 ,
'lat':66 },
'zoom': 1
},
width=500,
height=300,
margin={"r":0,"t":0,"l":0,"b":0}
)
fig.show()import requests
import plotly.graph_objects as go
# 1. 获取边界数据
url = "https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/World_Administrative_Divisions/FeatureServer/0/query"
params = {
'where': "COUNTRYAFF = 'China'",
'outFields': '*',
'returnGeometry': 'true',
'retrunRecords': 34,
'f': 'geojson'
}
response = requests.get(url, params=params)
data = response.json()
# 4. 创建地图可视化(使用Choroplethmapbox)
fig = go.Figure(go.Choroplethmapbox(
# geojson=data, # 直接使用原始几何数据
# locations=['Juneau'], # 对应feature的索引
# z=[1], # 颜色值(这里用固定值)
# colorscale=[[0, 'rgba(255,0,0,0.3)'], [1, 'rgba(255,0,0,0.3)']], # 固定半透明红色
# marker_opacity=0.3, # 整体透明度
# marker_line_width=1, # 边界线宽度
# marker_line_color='red', # 边界线颜色
# featureidkey="properties.NAME", # 关联属性字段
# showscale=False # 隐藏色标
geojson=data,
locations=[f['properties']['OBJECTID'] for f in data['features']], # 县名列表
z=[1]*len(data['features']), # 统一颜色值
colorscale=[[0, 'rgba(0,100,0,0.3)'], [1, 'rgba(0,100,0,0.3)']],
marker_opacity=0.6,
marker_line_width=0.8,
marker_line_color='yellow',
featureidkey="properties.OBJECTID",
showscale=False,
hovertext=[f['properties']['NAME'] for f in data['features']],
))
fig.update_layout(
mapbox={
'style': "white-bg",
'layers': [{
'below': 'traces',
'sourcetype': "raster",
'source': [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
]
}],
'center': {'lon':130 ,
'lat':50 },
'zoom': 1
},
width=500,
height=300,
margin={"r":0,"t":0,"l":0,"b":0}
)
fig.show()其他数据源
GEODATA-GDAM中国边界 :url = “https://geodata.ucdavis.edu/gadm/gadm4.1/json/gadm41_CHN_1.json”
亚洲高速公路 :https://hub.arcgis.com/datasets/a9f8d83a69fc4f2c92e5f83f87df6aaf_0/explore?location=35.590192%2C103.246694%2C14.93
url = "https://geodata.ucdavis.edu/gadm/gadm4.1/json/gadm41_CHN_1.json"
response = requests.get(url)
data = response.json()
# 4. 创建地图可视化(使用Choroplethmapbox)
fig = go.Figure(go.Choroplethmapbox(
# geojson=data, # 直接使用原始几何数据
# locations=['Juneau'], # 对应feature的索引
# z=[1], # 颜色值(这里用固定值)
# colorscale=[[0, 'rgba(255,0,0,0.3)'], [1, 'rgba(255,0,0,0.3)']], # 固定半透明红色
# marker_opacity=0.3, # 整体透明度
# marker_line_width=1, # 边界线宽度
# marker_line_color='red', # 边界线颜色
# featureidkey="properties.NAME", # 关联属性字段
# showscale=False # 隐藏色标
geojson=data,
locations=[f['properties']['NL_NAME_1'] for f in data['features']], # 县名列表
z=[1]*len(data['features']), # 统一颜色值
colorscale=[[0, 'rgba(0,100,0,0.3)'], [1, 'rgba(0,100,0,0.3)']],
marker_opacity=0.6,
marker_line_width=0.8,
marker_line_color='yellow',
featureidkey="properties.NL_NAME_1",
showscale=False
))
fig.update_layout(
mapbox={
'style': "white-bg",
'layers': [{
'below': 'traces',
'sourcetype': "raster",
'source': [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
]
}],
'center': {'lon':-152 ,
'lat':66 },
'zoom': 1
},
width=500,
height=300,
margin={"r":0,"t":0,"l":0,"b":0}
)
fig.show()Road
import requests
import plotly.graph_objects as go
# 1. 获取边界数据
url = "https://services-ap1.arcgis.com/iA7fZQOnjY9D67Zx/arcgis/rest/services/OSM_AS_Highways/FeatureServer/0/query"
# params = {
# 'where': "Shape.STWithin((41.5, 123.2, 42.1, 124.0))",
# 'outFields': '*',
# 'returnGeometry': 'true',
# 'f': 'geojson'
# }
params = {
'where': "1=1",
#'geometry': "{\"xmin\":123.2, \"ymin\":41.5, \"xmax\":124.0, \"ymax\":42.1, \"spatialReference\":{\"wkid\":4326}}",
'geometry': "{\"xmin\":123.3, \"ymin\":41.7, \"xmax\":123.5, \"ymax\":41.9, \"spatialReference\":{\"wkid\":4326}}",
'geometryType': 'esriGeometryEnvelope',
'inSR': 4326,
'outSR': 4326,
'returnGeometry': 'true',
#'resultRecordCount':1900,
'f': 'geojson',
'spatialRel': 'esriSpatialRelIntersects'
}
response = requests.get(url, params=params)
data = response.json()
# 2. 处理GeoJSON数据
lons = []
lats = []
i=1
for feature in data['features']:
i=i+1
geometry = feature['geometry']
if geometry['type'] == 'LineString':
coords = geometry['coordinates']
for lon, lat in coords:
lons.append(lon)
lats.append(lat)
# 添加None分隔不同线段
lons.append(None)
lats.append(None)
elif geometry['type'] == 'MultiLineString':
for line in geometry['coordinates']:
for lon, lat in line:
lons.append(lon)
lats.append(lat)
lons.append(None)
lats.append(None)
# 3. 创建地图可视化
fig = go.Figure(go.Scattermapbox(
mode="lines",
lon=lons,
lat=lats,
line=dict(width=1, color='red'),
hoverinfo='none'
))
fig.update_layout(
mapbox={
'style': "white-bg",
'layers': [{
'below': 'traces',
'sourcetype': "raster",
'source': [
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
]
}],
'center': {'lon':123.4 ,
'lat':41.75 },
'zoom': 10
},
width=500,
height=300,
margin={"r":0,"t":0,"l":0,"b":0}
)
fig.show()