Python多组条形图不显示排查及十六进制颜色设置
Fixing Your Grouped Bar Chart with Value Labels
Let's work through getting your bar chart displaying properly, plus tweak the colors to use hex codes as you requested.
Key Issues in Your Original Code
- Undefined variable: You referenced
xcordinax.set_xticklabels(xcord)but named your specialty listcordearlier. This would throw an error (even if it wasn't showing up explicitly), stopping the chart from rendering. - Overlapping bars:
rects1andrects2are plotted at the exact same x-position (ind), so they completely cover each other.rects3is placed way too far right, making the layout messy and unreadable. - Misaligned xticks: The
ax.set_xticks(ind+width)line doesn't match the position of your grouped bars, which would throw off label placement.
Corrected Code with Hex Colors & Proper Layout
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Load data (hardcoded here for reproducibility; uncomment your CSV line below) data = { 'Speciality': ['Big Data (Spark/Hadoop)', 'Data Analysis / Statistics', 'Data Journalism'], 'Very interested': [1332, 1688, 429], 'Somewhat interested': [729, 444, 1081], 'Not interested': [127, 60, 610] } pd_dataframe = pd.DataFrame(data) # pd_dataframe = pd.read_csv('Test-Barchart.csv') # Use this line for your actual file no_of_xaxis = pd_dataframe.Speciality.nunique() ind = np.arange(no_of_xaxis) width = 0.25 # Narrow width to fit 3 bars per specialty group # Extract data into lists cord = pd_dataframe['Speciality'].tolist() veryinterestedlist = pd_dataframe['Very interested'].tolist() somewhatlist = pd_dataframe['Somewhat interested'].tolist() notinterestedlist = pd_dataframe['Not interested'].tolist() # Set up chart with a larger size for readability fig, ax = plt.subplots(figsize=(10, 6)) # Plot each bar group with custom hex colors rects1 = ax.bar(ind - width, veryinterestedlist, width, color='#5bc0de', label='Very Interested') rects2 = ax.bar(ind, somewhatlist, width, color='#f0ad4e', label='Somewhat Interested') rects3 = ax.bar(ind + width, notinterestedlist, width, color='#d9534f', label='Not Interested') # Function to add value labels on top of bars def autolabel(rects): for rect in rects: h = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., h, f'{int(h)}', ha='center', va='bottom', fontsize=10) autolabel(rects1) autolabel(rects2) autolabel(rects3) # Fix xticks and labels ax.set_xticks(ind) ax.set_xticklabels(cord, rotation=15, ha='right') # Rotate labels to avoid overlap # Add finishing touches ax.legend() ax.set_title('Interest in Data Specialties', fontsize=14) ax.set_ylabel('Number of Respondents') plt.tight_layout() # Prevent label cutoff plt.show()
What Changed & Why
- Bar Positioning: We shifted each bar group by
-width,0, and+widthrelative toindso they sit side-by-side without overlapping. The narrower0.25width ensures all three bars fit neatly per specialty. - Variable Fix: Swapped
xcordforcordin the xtick labels to resolve the undefined variable error. - Hex Colors: Replaced color names like
'r'with your desired hex codes (e.g.,#5bc0de). You can swap these out for any hex color you want—just plug in the code as thecolorparameter. - Layout Improvements: Added a larger figure size, rotated x-labels for readability, and used
tight_layout()to stop labels from getting cut off. - Cleaner Setup: Used
plt.subplots()instead offig.add_subplot()for a more standard, readable matplotlib workflow.
The main reason your original code didn't display was the undefined xcord variable—even if the error wasn't visible, it would halt the chart rendering. The overlapping bars would have made the chart look broken even if it did load.
内容的提问来源于stack exchange,提问作者user1820530
相关产品推荐
相关产品推荐

