You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 xcord in ax.set_xticklabels(xcord) but named your specialty list cord earlier. This would throw an error (even if it wasn't showing up explicitly), stopping the chart from rendering.
  • Overlapping bars: rects1 and rects2 are plotted at the exact same x-position (ind), so they completely cover each other. rects3 is 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

  1. Bar Positioning: We shifted each bar group by -width, 0, and +width relative to ind so they sit side-by-side without overlapping. The narrower 0.25 width ensures all three bars fit neatly per specialty.
  2. Variable Fix: Swapped xcord for cord in the xtick labels to resolve the undefined variable error.
  3. 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 the color parameter.
  4. Layout Improvements: Added a larger figure size, rotated x-labels for readability, and used tight_layout() to stop labels from getting cut off.
  5. Cleaner Setup: Used plt.subplots() instead of fig.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:07:11