Python:调整雷达图上的x轴标签

2024-03-29 13:53:32 发布

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

我画了一张雷达图。但是,x标签与图表相交。如何调整其放置位置,使其不与网格冲突



# Libraries
import matplotlib.pyplot as plt
import pandas as pd
from math import pi

# Set data
#9,443  8,951  3,162  1,744  486  23,786 
# 16,019 24,004 8,049 8,729 415 57,218 
df = pd.DataFrame({
'group': ['1996','2016'],
'Natural Gas': [2079, 12304],
'Petroleum Products': [17203, 30348],
'Coal & Coke': [727, 1785],
'Biodiesel': [0, 389],
'Electricity': [3777, 12392]
})

# ------- PART 1: Create background

# number of variable
categories=list(df)[1:]
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)]
angles += angles[:1]

# Initialise the spider plot
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[:-1], categories)

# Draw ylabels
ax.set_title('Energy Consumption by Fuel Type (Mtoe)',  position=(0.5, 1.1), ha='center', fontweight="bold")
ax.set_rlabel_position(0)
plt.yticks([10000,20000,30000,40000], ["10","20","30","40"], color="grey", size=8, fontweight="bold")
plt.ylim(0,40000)

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

# Plot each individual = each line of the data
# I don't do a loop, because plotting more than 3 groups makes the chart unreadable

# Ind1
values=df.loc[0].drop('group').values.flatten().tolist()
values += values[:1]
ax.plot(angles, values, linewidth=1, linestyle='solid', label="1996, 23.786 Mtoe", color="green")
ax.fill(angles, values, 'green', alpha=0.4)

# Ind2
values=df.loc[1].drop('group').values.flatten().tolist()
values += values[:1]
ax.plot(angles, values, linewidth=1, linestyle='solid', label="2016, 57.218 Mtoe",color="purple")
ax.fill(angles, values, 'purple', alpha=0.2)

# Add legend
plt.legend(loc='upper right', bbox_to_anchor=(0.5, 0.001))


输出图表如下所示:

output pic

请导游。 Tq


Tags: oftheimportdfplotgrouppiplt