雷达图Matplotlib Python:如何设置标签对齐 [英] Radar Plot Matplotlib Python : how to set label alignment

查看:1355
本文介绍了雷达图Matplotlib Python:如何设置标签对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将雷达图的标签与轴对齐,我遇到了困难。



没有标签对齐,我的标签将居中并超出轴线。



当我将标签的前半部分(图的右侧)设置为左对齐时,将下半部分的对齐方式设置为右对齐时, 圆形对齐方式



为此,我在xticklabels中循环并设置了水平对齐方式。

 #每个变量画一个斧头+添加标签标签
plt.xticks(角度,类别)
标签,i用拉链(ax.get_xticklabels(),range(0,len(angles))):如果i< len(angles / 2):

angle_text = angles [i] *(-180 / pi)+ 90
#label.set_horizo​​ntalalignment('left')

else:
angle_text = angles [i] *(-180 / pi)-90
#label。 set_horizo​​ntalalignment('right')
label.set_rotation(angle_text)

我想有一个正确的方法来做到这一点,我不能找出答案,因为我不知道它是否应该考虑偏移量,平移或如何调整极坐标。



感谢您的帮助



Paul



以下是完整代码,以获取更多信息

 从math import pi 
import matplotlib.pyplot as plt
%matplotlib内联
导入熊猫为pd

##生成数据
labels_test = []
for i在范围(0,40)中:
labels_test .append( Fooooooooo + str(i))
pd_radar = pd.DataFrame(data = np.random.randint(low = 0,high = 10,size =(2,40)),列= labels_test )

#变量
的类别数量= list(pd_radar)
N = len(类别)

#每个轴的角度是多少在情节? (我们除以图/变量数)
角度= [n / float(N)* 2 * pi为n范围(N)中的pi]

#初始化蜘蛛图
fig = plt.figure(figsize =(20,10))
轴= plt.subplot(111,polar = True)

#如果您希望第一个轴位于top:
ax.set_theta_offset(pi / 2)
ax.set_theta_direction(-1)

#为每个变量绘制一个斧头+添加标签,但
plt。 xticks(角度,类别)
用于标签,zip中的i(ax.get_xticklabels(),range(0,len(angles))):
如果i< len(angles / 2):
angle_text = angles [i] *(-180 / pi)+90
label.set_horizo​​ntalalignment('left')

else:
angle_text = angles [i] * (-180 / pi)-90
label.set_horizo​​ntalalignment('right')
label.set_rotation(angle_text)
#绘制ylabels
ax.set_rlabel_position(0)


#-------第2部分:添加图表

#绘制数据的每一行

#Ind1
values0 = pd_radar.iloc [0] .values.flatten()。tolist()
ax.plot(angles,values0,linewidth = 1,linestyle ='solid',label = Label 1,color ='yellow')
ax.fill(angles,values0,'r' ,alpha = 0.1,color ='yellow')

#Ind2
values1 = pd_radar.iloc [1] .values.flatten()。tolist()
ax.plot (angles,values1,linewidth = 1,linestyle ='solid',label = Label 2,color ='deepskyblue')
ax.fill(angles,values1,'r',color ='deepskyblue', alpha = 0.1)

#添加图例
plt.show()


解决方案

当前代码



也可以是锚点 ,在这种情况下,首先将文本对齐,然后再旋转。





因此,为了使极坐标图上指向外部的ticklabels,您需要将文本的对齐方式设置为 left ,然后将旋转模式设置为锚。

 对于标签,zip中的腐烂(ax.get_xticklabels(),滴答):
label.set_rotation(rot * 180./np.pi)
label.set_horizo​​ntalalignment( left)
label.set_rotation_mode( anchor)

完整示例:

  import numpy as np 
import matplotlib.pyplot as plt

fig = plt.figure(figsize =(5,5))
ax = plt.subplot(111,polar = True)

ticks = np .linspace(0,2 * np.pi,20,endpoint = False)
text = lambda: .join(np.random.choice(list( manuladefil),size = 10))
labels = [text()for _ in range(len(ticks))]

plt.xticks(ticks,labels,size = 16)
for label,rot in zip( ax.get_xticklabels(),滴答声:
label.set_rotation(rot * 180. / np.pi)
label.set_horizo​​ntalalignment( left)
label.set_rotation_mode( anchor)

plt.tight_layout()
plt.show()


I am trying to align labels of my radar plot with axis and I face difficulties.

Without label alignment, my labels are centered and exceed the axis line .

When I set for the first half of my labels (the right side of the figure) alignment to left and for the second half the alignment to the right I get a non "circular" alignment

To do so I looped within xticklabels and set horizontal alignment.

# Draw one axe per variable + add labels labels yet
plt.xticks(angles, categories)
for label,i in zip(ax.get_xticklabels(),range(0,len(angles))):
    if i<len(angles)/2:
        angle_text=angles[i]*(-180/pi)+90
        #label.set_horizontalalignment('left')

    else:
        angle_text=angles[i]*(-180/pi)-90
        #label.set_horizontalalignment('right')
    label.set_rotation(angle_text)

I guess there is a proper way to do this and I can't figure it out, as I don't know if it should consider an offset, a translation or how to adapt the polar coordinate to do so.

Thanks for your help

Paul

Here follows the full code for more information

from math import pi
import matplotlib.pyplot as plt
%matplotlib inline
import pandas as pd

## Generate Data
labels_test=[]
for i in range(0,40):
    labels_test.append("Fooooooooo"+str(i))
pd_radar=pd.DataFrame(data=np.random.randint(low=0, high=10, size=(2, 40)),columns=labels_test)

# number of variable
categories=list(pd_radar)
N = len(categories)

# What will be the angle of each axis in the plot? (we divide the plot / number of variable)
angles = [n / float(N) * 2 * pi for n in range(N)]

# Initialise the spider plot
fig=plt.figure(figsize=(20,10))
ax = plt.subplot(111, polar=True)

# If you want the first axis to be on top:
ax.set_theta_offset(pi / 2)
ax.set_theta_direction(-1)

# Draw one axe per variable + add labels labels yet
plt.xticks(angles, categories)
for label,i in zip(ax.get_xticklabels(),range(0,len(angles))):
    if i<len(angles)/2:
        angle_text=angles[i]*(-180/pi)+90
        label.set_horizontalalignment('left')

    else:
        angle_text=angles[i]*(-180/pi)-90
        label.set_horizontalalignment('right')
    label.set_rotation(angle_text)
# Draw ylabels
ax.set_rlabel_position(0)


# ------- PART 2: Add plots

# Plot each line of the data 

# Ind1
values0=pd_radar.iloc[0].values.flatten().tolist()
ax.plot(angles, values0, linewidth=1, linestyle='solid', label="Label 1",color='yellow')
ax.fill(angles, values0, 'r', alpha=0.1,color='yellow')

# Ind2
values1=pd_radar.iloc[1].values.flatten().tolist()
ax.plot(angles, values1, linewidth=1, linestyle='solid', label="Label 2",color='deepskyblue')
ax.fill(angles, values1, 'r',color='deepskyblue', alpha=0.1)

# Add legend
plt.show()

解决方案

The code currently does not run with matplotlib 2.2. The following solution works however with version 2.0.2 that the OP is using. For a workaround using newer versions, see this question.

Texts in matplotlib have a rotation mode.

The rotation mode can be "default", in which case the text is first rotated and then aligned

or it can be "anchor", in which case the text is first aligned and then rotated.

Therefore, in order to have the ticklabels pointing outwards on the polar plot, you would want to set the alignment of the text to "left", but then set the rotation mode to "anchor".

for label,rot in zip(ax.get_xticklabels(),ticks):
    label.set_rotation(rot*180./np.pi)
    label.set_horizontalalignment("left")
    label.set_rotation_mode("anchor")

Full example:

import numpy as np
import matplotlib.pyplot as plt

fig=plt.figure(figsize=(5,5))
ax = plt.subplot(111, polar=True)

ticks = np.linspace(0, 2*np.pi, 20, endpoint=False)
text = lambda : "".join(np.random.choice(list("manuladefil"), size=10))
labels = [text() for _ in range(len(ticks))]

plt.xticks(ticks, labels, size=16)
for label,rot in zip(ax.get_xticklabels(),ticks):
    label.set_rotation(rot*180./np.pi)
    label.set_horizontalalignment("left")
    label.set_rotation_mode("anchor")

plt.tight_layout()
plt.show()

这篇关于雷达图Matplotlib Python:如何设置标签对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆