Python Matplotlib:如何在气泡图中的每个元素旁边放置标签

Python Matplotlib : how to put label next to each element in the bubble plot

我有这样的气泡图,我愿意在每个气泡(他们的名字)旁边贴上标签。有人知道怎么做吗?

@Falko 提到了另一个 post,它表明您应该寻找轴的 text 方法。但是,您的问题比这复杂得多,因为您需要实现一个 offset ,它会随着 "bubble" (标记)的大小动态缩放。这意味着您将研究 matplotlib 的 transformation methods

由于您没有提供一个简单的示例数据集来进行实验,我使用了一个免费提供的数据集:1974 年的地震。在这个例子中,我绘制了地震的深度与日期它发生了,用地震的震级作为 bubbles/markers 的大小。我将这些地震发生的位置 附加到标记 旁边, 而不是在 内(这要容易得多:忽略偏移并设置ha='center' 在对 ax.text 的调用中)。

请注意,此代码示例的大部分只是关于获取一些数据集来玩弄。您真正需要的只是带有偏移量的 ax.text 方法。

from __future__ import division  # use real division in Python2.x
from matplotlib.dates import date2num
import matplotlib.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Get a dataset
data_url = 'http://datasets.flowingdata.com/earthquakes1974.csv'
df = pd.read_csv(data_url, parse_dates=['time'])
# Select a random subset of that dataframe to generate some variance in dates, magnitudes, ...
data = np.random.choice(df.shape[0], 10)
records = df.loc[data]
# Taint the dataset to add some bigger variance in the magnitude of the 
# quake to show that the offset varies with the size of the marker
records.mag.values[:] = np.arange(10)
records.mag.values[0] = 50
records.mag.values[-1] = 100

dates = [date2num(dt) for dt in records.time]
f, ax = plt.subplots(1,1)
ax.scatter(dates, records.depth, s=records.mag*100, alpha=.4)  # markersize is given in points**2 in recentt versions of mpl
for _, record in records.iterrows():
    # Specify an offset for the text annotation:
    # it is approx the radius of the disc + 10 points to the right
    dx, dy = np.sqrt(record.mag*100)/f.dpi/2 + 10/f.dpi, 0.  
    offset = transforms.ScaledTranslation(dx, dy, f.dpi_scale_trans)
    ax.text(date2num(record.time), record.depth, s=record.place,
        va='center',  ha='left',
        transform=ax.transData + offset)
ax.set_xticks(dates)
ax.set_xticklabels([el.strftime("%Y-%M") for el in records.time], rotation=-60)
ax.set_ylabel('depth of earthquake')
plt.show()

对于这样的 运行,我得到: 由于标签重叠,绝对不漂亮,但它只是一个示例,展示如何使用 matplotlib 中的 transforms 动态添加标签偏移量。