matplotlib可视化正负比例图

2024-09-29 00:15:14 发布

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

我试图制作与下面相同的图表,不知道matplotlib是否有类似的图表

下表是R包中STM主题模型的结果

我在Python中使用DMR获得probs值:

array([[0.07204196, 0.04238116],
       [0.04518877, 0.30546978],
       [0.0587892 , 0.19870868],
       [0.16710107, 0.07182639],
       [0.128209  , 0.02422131],
       [0.15264449, 0.07237352],
       [0.2250081 , 0.06986096],
       [0.1337716 , 0.10750801],
       [0.01197221, 0.06736039],
       [0.00527367, 0.04028973]], dtype=float32)

这些是结果,左边是否定的,右边是肯定的

负-正比例图示例:

Example of negative positive proportion chart


Tags: 模型示例主题matplotlib图表arraydtypestm
2条回答

可以创建与您包含的图像非常接近的内容。我知道右栏应该是负数,而右栏应该是正数

首先将数据设为负数:

import numpy as np

arr = np.array([[0.07204196, 0.04238116],
                [0.04518877, 0.30546978],
                [0.0587892 , 0.19870868],
                [0.16710107, 0.07182639],
                [0.128209  , 0.02422131],
                [0.15264449, 0.07237352],
                [0.2250081 , 0.06986096],
                [0.1337716 , 0.10750801],
                [0.01197221, 0.06736039],
                [0.00527367, 0.04028973]], dtype="float32")

# Make the right col negative
arr[:, 0] *= -1

然后我们可以这样画:

from string import ascii_lowercase
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

for y, x in enumerate(arr.flatten()):
    # Get a label from the alphabet
    label = ascii_lowercase[y]
    # Plot the point
    ax.plot(x, y, "o", color="black")
    # Annotate the point with the label
    ax.annotate(label, xy=(x, y), xytext=(x - 0.036, y), verticalalignment="center")

# Add the vertical line at zero
ax.axvline(0, ls=" ", color="black", lw=1.25)

# Make the x axis equal
xlim = abs(max(ax.get_xlim(), key=abs))
ax.set_xlim((-xlim, xlim))

# Remove y axis
ax.yaxis.set_visible(False)

# Add two text labels for the x axis
for text, x in zip(["Negative", "Positive"], ax.get_xlim()):
    ax.text(x / 2, -3.75, f"{text} Reviews", horizontalalignment="center")

哪些产出:

Chart with annotated points

如果需要更改打印或x轴上文本的位置,可以调整对ax.annotateax.text的调用中的值

我不确定问题的关键部分是什么。也就是说,您更感兴趣的是基于类别标记各个点,还是更关心带有一条直线的唯一圆。对于提供的数组,数据表示的内容有点混乱

我假设每个子列表代表一个类别。考虑到这一点,我所做的是为值的差异制作一个单独的列(delta),然后将它们与索引进行对比

# New column (delta) with styling
df['delta'] = df[0]-df[1]
col = np.where(df.delta>0,'g',np.where(df.index<0,'b','r'))

fig, ax = plt.subplots(figsize =(10,7))


# Style it up a bit

plt.title('Differnece in Topic Proportion (Negative vs Positive)')
plt.xlabel('Net Review Score')

plt.ylabel('Index Number')
plt.tight_layout()
plt.savefig("Evolution of rapport of polarisation - (Aluminium).png")


plt.scatter(df['delta'], df.index,  s=None, c=col, marker=None, linewidth=2)


plt.axvline(x = 0, color = 'b', label = 'axvline - full height', linestyle=" " ) 

从中可以看出:

enter image description here

相关问题 更多 >