繁体   English   中英

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

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

我有这样的气泡图,并且我愿意在每个气泡(它们的名称)旁边贴上标签。 有谁知道该怎么做?

在此处输入图片说明

@Falko引用了另一篇文章,该文章表明您应该在寻找轴的text方法。 但是,您的问题要比这涉及得多,因为您需要实现一个随“气泡”(标记)的大小动态缩放的偏移量 这意味着您将研究matplotlib的转换方法

由于您没有提供简单的示例数据集进行实验,因此我使用了一个免费的数据集:1974年的地震。在此示例中,我使用以下方法绘制了地震深度与发生日期的关系图:地震的程度,即气泡/标记的大小。 我将这些地震发生的位置附加在标记旁边而不是在 标记旁边 (这更容易:忽略偏移量,并在ax.text的调用中设置ha='center' )。

请注意,此代码示例的大部分只是关于获取一些数据集以作为玩具。 您真正需要的只是带有偏移量的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为标签动态添加偏移量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM