如何在matplotlib中添加水平线作为注释(轴之外)?

2024-04-25 06:47:06 发布

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

我正在用seaborn和matplotlib绘制条形图。我想用两个词和一条线来注释这个情节。在

下面是我生成这个数字的策略(很抱歉提供了plot_data,但它太大了):

        plt.figure()
        ax = seaborn.barplot(x='cell_line', y='DeltaCt', data=plot_data, hue='time')
        plt.title('Baseline: {}'.format(g))
        plt.ylabel('DeltaCt')
        plt.xlabel('')
        trans = ax.get_xaxis_transform()
        ax.annotate('Neonatal', xy=(0.4, -0.1), xycoords=trans)
        plt.show()

从而产生: enter image description here

不过,我需要在这张图上的x轴和“新生儿”注释之间再画一条黑线。这样地: enter image description here


Tags: transdataplotmatplotlib绘制plt数字seaborn
1条回答
网友
1楼 · 发布于 2024-04-25 06:47:06

一些相关问题:

这里需要一条垂直线,但这条线必须是沿x轴的数据坐标。因此,您可以使用ax.get_xaxis_transform()。要使线在轴外可见,请使用clip_on = False。在

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

plot_data = pd.DataFrame({"cell_line": np.random.choice(list("ABCDEFG"), size=150),
                          'DeltaCt' : np.random.rayleigh(5,size=150),
                          "time":np.random.choice([0,96], size=150)})

plt.figure()
ax = sns.barplot(x='cell_line', y='DeltaCt', data=plot_data, hue='time', 
                 order=list("ABCDEFG"))
plt.title('Baseline: {}'.format("H"))
plt.ylabel('DeltaCt')
plt.xlabel('')
trans = ax.get_xaxis_transform()
ax.annotate('Neonatal', xy=(1, -.1), xycoords=trans, ha="center", va="top")
ax.plot([-.4,2.4],[-.08,-.08], color="k", transform=trans, clip_on=False)
plt.show()

enter image description here

相关问题 更多 >