在matplotlib中一个在另一个上面打印条形图

csbfibhn  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(77)

我试着按照剧本…

import matplotlib.pyplot as plot
import pandas as pd

data = {"PEOI": [100,129,203,406,92,69,69,51,55,34,371], "PCHOI":[-3,-3,-4,10,37,2,-6,16,7,2,-44], "STKS":[4800,4810,4820,4840,4850,4860,4880,4900,4910,4920,4940], "CCHOI":[50,74,45,617,54,2,35,3,3,10,13], "CEOI":[177,182,67,562,118,135,112,30,32,15,184]}     
df = pd.DataFrame(data);

ax1 = df.plot.bar(x="STKS", y=["CEOI","PEOI"], rot=90, width = 0.9, title ="OPEN INTEREST BUILDUP", figsize=(10, 6), fontsize=20)
ax1.set_xlabel("STRIKES", fontweight ='bold', fontsize=25)

ax1.set_ylabel("CHANGE IN OI", fontweight ='bold', fontsize=25)
plot.show(block=True);

字符串
现在我有两个疑问…
1-如何使“CEOI”和“PEOI”条打印一个在另一个上面(完全重叠),具有类似的网格线,如下图

2-我需要两个图在同一时间(子图)的数据集从我的DataFrame....
(a)PEOI、CEOI、STKS
(b)PCHOI、CCHOI、STKS

t0ybt7op

t0ybt7op1#

我不认为你可以用pandas做你想做的事情,所以我们必须使用matplotlib从头开始构建这个图。对于在彼此前面的条形图,只需制作两个条形图,给它们相同的x值,并以不同的宽度绘制它们。对于子图,我创建了一个列表,数据将进入哪个图,并通过它们沿着轴循环,以创建图。代码的其余部分用于格式化(字体大小和旋转、标签等)。

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

data = {"PEOI": [100, 129, 203, 406, 92, 69, 69, 51, 55, 34, 371],
        "PCHOI": [-3, -3, -4, 10, 37, 2, -6, 16, 7, 2, -44],
        "STKS": [4800, 4810, 4820, 4840, 4850, 4860, 4880, 4900, 4910, 4920, 4940],
        "CCHOI": [50, 74, 45, 617, 54, 2, 35, 3, 3, 10, 13],
        "CEOI": [177, 182, 67, 562, 118, 135, 112, 30, 32, 15, 184]}
df = pd.DataFrame(data)

min_diff_x = np.diff(df.STKS).min()
w1 = 0.8*min_diff_x
w2 = 0.5*min_diff_x

fig, axes = plt.subplots(2, 1, figsize=(10,15))
for (y1, y2), ax in zip([("PEOI", "CEOI"), ("PCHOI", "CCHOI")], axes):
    ax.bar(df["STKS"], df[y1], width=w1, label=y1)
    ax.bar(df["STKS"], df[y2], width=w2, label=y2)
    ax.set_xlabel("STRIKES", fontweight="bold", fontsize=25)
    ax.set_ylabel("CHANGE IN OI", fontweight="bold", fontsize=25)
    ax.tick_params(labelsize=20)
    ax.tick_params(axis="x", rotation=90)
    ax.legend()
    ax.grid()
fig.suptitle("OPEN INTEREST BUILDUP", fontsize=20)
fig.tight_layout()

字符串


的数据

相关问题