python柱状图标签重叠_python – 饼图标签重叠相同的值.

您可以手动调整标签位置,但这样可以为这样一个简单的请求提供更多代码.您可以通过检查放置的位置来检测重复标签组.

这是一个示例,其中一些随机数据复制了重叠标签的出现:

import matplotlib.pyplot as plt

import numpy as np

from collections import Counter

import datetime

# number slices of pie

num = 10

# generate some labels

dates = [datetime.datetime(2014,1,1) + datetime.timedelta(days=np.random.randint(1,20)) for i in range(num)]

labels = [d.strftime('%d-%m-%Y') for d in dates]

# generate some values

values = np.random.randint(2,10, num)

# force half of them to be zero

mask = np.random.choice(num, num // 2, replace=False)

values[mask] = 0

# pick some colors

colors = plt.cm.Blues(np.linspace(0,1,num))

fig, ax = plt.subplots(figsize=(9.0, 6.10), subplot_kw={'aspect': 1})

wedges, labels, pcts = ax.pie(values, colors=colors, labels=labels, autopct='%1.1f%%')

# find duplicate labels and the amount of duplicates

c = Counter([l.get_position() for l in labels])

dups = {key: val for key, val in c.items() if val > 1}

# degrees of spacing between duplicate labels

offset = np.deg2rad(3.)

# loop over any duplicate 'position'

for pos, n in dups.items():

# select all labels with that position

dup_labels = [l for l in labels if l.get_position() == pos]

# calculate the angle with respect to the center of the pie

theta = np.arctan2(pos[1], pos[0])

# get the offsets

offsets = np.linspace(-(n-1) * offset, (n-1) * offset, n)

# loop over the duplicate labels

for l, off in zip(dup_labels, offsets):

lbl_radius = 1.3

# calculate the new label positions

newx = lbl_radius * np.cos(theta + off)

newy = lbl_radius * np.sin(theta + off)

l.set_position((newx, newy))

# rotate the label

rot = np.rad2deg(theta + off)

# adjust the rotation so its

# never upside-down

if rot > 90:

rot += 180

elif rot < -90:

rot += 180

# rotate and highlight the adjusted labels

l.set_rotation(rot)

l.set_ha('center')

l.set_color('#aa0000')

我故意只修改重叠标签以突出显示效果,但您可以以类似的方式更改所有标签以创建统一样式.旋转可以更容易地自动分隔它们,但您可以尝试其他放置方式.

请注意,它只检测真正相同的展示位置,如果您的值为[0,0.00001,2,10],它们可能仍会重叠.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值