matplotlib 具有多条线和两种不同样式的Python图数据框

isr3a4wc  于 2023-01-17  发布在  Python
关注(0)|答案(1)|浏览(105)

假设你有一个 Dataframe df,它应该用两种不同的线条样式来绘制。每一条带有“X_Y”==“Y”的线都应该是虚线。我想知道是否有比下面更快更有效的方法?

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        "Point": (
            "1", "1", "2", "2", "3", "3", "4", "4", "5", "5"
        ),
        "X_Y": (
            "X", "Y", "X", "Y", "X", "Y", "X", "Y", "X", "Y",
        ),
        0: (
            70, 67, 66.7, 68.8, 66.2, 69.5, 68.5, 67.7, 68.8, 67.72,
        ),
        1: (
            69, 68.2, 66.5, 68.1, 66.7, 70, 68.1, 66.7, 66.08, 65.72,
        ),
        2: (
            71, 68, 67.75, 67.8, 67.72, 70.3, 67.6, 66.5, 69.08, 66.72,
        ),
        3: (
            70.5, 67.3, 67.5, 64.8, 68.3, 69.3, 68.6, 68.5, 70.08, 67.72,
        ),
    }
)

print(df)

vals = ["X", "Y"]
styles = ["-", "--"]

plt.figure()
plt.grid(True)
for val, style in zip(vals, styles):
    dff = df.loc[df["X_Y"] == val].drop(["Point", "X_Y"], axis=1).T

    plt.plot(dff, linestyle=style)
    
plt.show()
f4t66c6m

f4t66c6m1#

您可以稍微转换一下 Dataframe ,使绘图更直观:

fig, ax = plt.subplots(1, 1)

df_unstacked = df.set_index(["X_Y", "Point"]).stack().unstack(["X_Y", "Point"])

df_unstacked["X"].plot(ax=ax, linestyle="-")
df_unstacked["Y"].plot(ax=ax, linestyle="--")

ax.grid(True)
ax.get_legend().remove()
ax.set_xlabel("")

print(df_unstacked.sort_index(axis=1))

X_Y       X                                Y                         
Point     1      2      3     4      5     1     2     3     4      5
0      70.0  66.70  66.20  68.5  68.80  67.0  68.8  69.5  67.7  67.72
1      69.0  66.50  66.70  68.1  66.08  68.2  68.1  70.0  66.7  65.72
2      71.0  67.75  67.72  67.6  69.08  68.0  67.8  70.3  66.5  66.72
3      70.5  67.50  68.30  68.6  70.08  67.3  64.8  69.3  68.5  67.72

相关问题