Matplotlib表中的垂直线和水平线

9w11ddsr  于 2023-08-06  发布在  其他
关注(0)|答案(2)|浏览(138)

我需要使用Matplotlib绘制一个DataFrame。水平线和垂直线的x和y值取决于第一个索引的宽度和高度。然而,我发现axhline在y=0处绘制水平线。然而,Axvline做得很正确。

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

df = pd.DataFrame(np.random.randn(8, 4), columns=["A", "B", "C", "D"])

fig, ax = plt.subplots()

tbl = ax.table(
    cellText=df.values,
    rowLabels=df.index,
    colLabels=df.columns,
    cellLoc="center",
    loc="center",
    fontsize=20,
    edges="open",
)
ax.axvline(x=tbl[1, -1].get_width(), color="blue", lw=1)
ax.axhline(y=tbl[1, -1].get_bbox().ymax, color="red", lw=1)
ax.axis("off")

字符串


的数据
我意识到如果我硬编码y值,我就可以画直线了

# ...
ax.axhline(y=0.6578, color="red", lw=1)
# ...



如何使用第一个索引高度位置使axhline正确工作?

4ngedf3f

4ngedf3f1#

您面临的问题是,在绘制轴线之前,需要先绘制表格。如果您在ax.table(..)之后,axvline()axhline()之前添加plt.draw(),它将工作。
x1c 0d1x的数据
完整更新代码…(只有一个额外的行:-))

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

df = pd.DataFrame(np.random.randn(8, 4), columns=["A", "B", "C", "D"])

fig, ax = plt.subplots()

tbl = ax.table(
    cellText=df.values,
    rowLabels=df.index,
    colLabels=df.columns,
    cellLoc="center",
    loc="center",
    fontsize=20,
    edges="open",
)

plt.draw()  ## The added line

ax.axvline(x=tbl[1, -1].get_width(), color="blue", lw=1)
ax.axhline(y=tbl[1, -1].get_bbox().ymax, color="red", lw=1)
ax.axis("off")

字符串

u4dcyp6a

u4dcyp6a2#

还可以控制地物和轴的尺寸:

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

df = pd.DataFrame(np.random.randn(8, 4), columns=["A", "B", "C", "D"])

# Set dimensions
fig, ax = plt.subplots(figsize=df.shape)
ax.axis([0, df.shape[1], df.shape[0], -1]) # xmin, xmax, ymin, ymax

tbl = ax.table(
    cellText=df.values,
    rowLabels=df.index,
    colLabels=df.columns,
    cellLoc="center",
    # loc="center",  # <- don't let matplotlib handle the position
    bbox=(0, 0, 1, 1),  # <- Force the bounding box
    fontsize=20,
    edges="open",
)

ax.axvline(x=0, color="blue", lw=1)
ax.axhline(y=0, color="red", lw=1)
ax.axis('off')
plt.show()

字符串
输出量:


的数据

相关问题