是否有一种使用Plotly express显示多个子地块的方法

2024-06-07 01:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我很想知道是否有一个相当于:

import pandas as pd
import numpy as np

data = pd.DataFrame({'Day':range(10),
                     'Temperature': np.random.rand(10), 
                     'Wind': np.random.rand(10),
                     'Humidity': np.random.rand(10),
                     'Pressure': np.random.rand(10)})

data.set_index('Day').plot(subplots=True, layout=(2,2), figsize=(10,5))
plt.tight_layout()

enter image description here

它生成与matplotlib图表相反的绘图图形


Tags: importnumpydataframepandasdataasnprange
2条回答
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# using your sample data

fig = make_subplots(rows=2, cols=2, start_cell="bottom-left")

fig.add_trace(go.Scatter(x=data.index, y=data.Temperature, name='Temp'),
              row=1, col=1, )

fig.add_trace(go.Scatter(x=data.index, y=data.Wind, name='Wind'),
              row=1, col=2)

fig.add_trace(go.Scatter(x=data.index, y=data.Humidity, name='Humidity'),
              row=2, col=1)

fig.add_trace(go.Scatter(x=data.index, y=data.Pressure, name='Pressure'),
              row=2, col=2)

fig.show()

enter image description here

对于plotly express解决方案:
您可以使用pd.melt()在同一列中获取所有变量:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    'Day':range(10),
    'Temperature': np.random.rand(10), 
    'Wind': np.random.rand(10),
    'Humidity': np.random.rand(10),
    'Pressure': np.random.rand(10),})

df_melt = df.melt(
    id_vars='Day', 
    value_vars=['Temperature', 'Wind', 'Humidity', 'Pressure'])

您的数据帧现在看起来是这样的,变量名位于名为“variable”的列中,值位于名为“value”的列中:

    Day variable    value
0   0   Temperature 0.609
1   1   Temperature 0.410
2   2   Temperature 0.194
3   3   Temperature 0.663
4   4   Temperature 0.351

现在您可以使用px.scatter()和参数facet_col来获得多个绘图:

fig = px.scatter(
    df_melt, 
    x='Day', 
    y='value', 
    facet_col='variable', 
    facet_col_wrap=2, 
    color='variable', 
    width=800,
)

这将导致以下绘图: plotly express facet_col instead of subplots

现在在您的示例中,所有变量都具有相同的值范围。但如果情况并非如此,则可能需要确保每个绘图在y轴上都有自己的范围。这可以通过以下方式完成:

fig.update_yaxes(showticklabels=True, matches=None)

有关刻面图的更多信息可在此处找到:
https://plotly.com/python/facet-plots/

相关问题 更多 >