pandas 更改图形的起点(Y轴)

jjhzyzn0  于 2023-06-28  发布在  其他
关注(0)|答案(1)|浏览(142)

数据集:

我有上面的数据集。我需要绘制一个图,其中y轴的起点需要为0,而不管数据集中的值如何。X轴是索引(时间),y轴是Jolt 1、Jolt 2、…
我有一个图表显示2个不同的图(蓝色曲线从y=0开始)。我希望橙子图也从0开始,以便直观地比较趋势。
图:

下面是代码

import pandas as pd
import matplotlib.pyplot as plt

df.set_index('Time').plot()
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))

如何修改代码以获得所需的输出?

ws51t4hk

ws51t4hk1#

您可以将'Time'列设置为dataframe的索引:

df = df.set_index('Time')

然后你可以循环其余的列,并绘制它们相对于dataframe索引。为了使所有行都从0开始,你必须在每一列中减去索引为0的相应起始点:

for column in df.columns:
    ax.plot(df.index, df[column] - df.loc[0, column], label = column)

完整代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame()
df['Time'] = np.arange(0, 0.6, 0.1)
df['Jolt 1'] = np.random.rand(len(df['Time']))
df['Jolt 2'] = np.random.rand(len(df['Time'])) + np.random.randint(low = -5, high = 5)
df['Jolt 3'] = np.random.rand(len(df['Time'])) + np.random.randint(low = -5, high = 5)
df = df.set_index('Time')

fig, ax = plt.subplots()

for column in df.columns:
    ax.plot(df.index, df[column] - df.loc[0, column], label = column)

ax.legend(frameon = True)

plt.show()

Plot

相关问题