如何在matplotlib的分组条形图聊天中对齐XTick?

2024-06-09 18:19:56 发布

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

之前我一直在使用MATLAB绘制图形,但现在我正在学习python。我想在x-tick上平等地组织酒吧。例如,在下面列出的问题中,我希望在x-tick标签的每一侧有两个条。我已经把代码放在这里了,还有我想做的数字

另外,在我学习python的过程中,我希望得到关于我的代码的反馈(尽管我接受了在线教程的帮助)。我怎样才能做得更好

import pandas as pd  import matplotlib import matplotlib.pyplot as plt
import numpy as np

raw_data = {'Load': ['50', '100'], 'Diesel': [1.738, 1.689], 'D59O41':
[1.71, 1.649],'D74Eu26': [1.71, 1.649], 'D59T41': [1.748, 1.702]}

df = pd.DataFrame(raw_data, columns = ['Load', 'Diesel', 'D59O41',
'D74Eu26', 'D59T41']) df;

pos = (50,100) 

n_groups = 2

# Setting the positions and width for the bars 

index = np.arange(n_groups)
width = 10 
r1 = pos 
r2 = [x + width for x in r1] 
r3 = [x + width for x in r2] 
r4 = [x + width for x in r3]

# Plotting the bars 

fig, ax = plt.subplots(figsize=(10,5))

plt.bar(r1, df['Diesel'], width, alpha=1, lw =1.8, edgecolor='black',
facecolor='black') 


plt.bar(r2, df['D59O41'], width, alpha=1,lw =2,
edgecolor='black', facecolor='none') 

plt.bar(r3, df['D74Eu26'], width, alpha=0.65,lw =2, edgecolor='red', 
facecolor='red') 

plt.bar(r4, df['D59T41'], width, alpha=0.65,lw =2, edgecolor='red', 
facecolor='none')


# Set the y axis label 

ax.set_ylabel('Fractal dimension')

# Set the x axis label 

ax.set_xlabel('Load')

# Set the chart's title

ax.set_title('Test Figure')

# Set the position of the x ticks

ax.set_xticks([p*1.1 + width for p in pos])


# Set the labels for the x ticks 

ax.set_xticklabels([50, 100])

# Setting the x-axis and y-axis limits

plt.xlim(min(pos)-width, max(pos)+width*6) 
plt.ylim([0, 2.5])

# Adding the legend and showing the plot 

plt.legend(['Diesel', 'D59O41', 'D74E26', 'D59T41'], loc='upper right')
plt.savefig('test_figure.tif', format='tif', dpi=300) 
plt.show()

Tags: theinposimportdfforbarplt