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

使用Plotly创建柱状图的技术求助(附数据及部分代码)

Complete & Optimized Plotly Bar Chart Code

Hey there! Let's get your bar chart working smoothly. First, note that datag.ix is deprecated in newer pandas versions—we'll use .iloc instead for reliable positional indexing. Here's the full, optimized code with explanations:

import plotly.graph_objs as go
import plotly.offline as offline

# Extract your data (replace datag with your actual DataFrame)
x_values = datag.iloc[:, 0].tolist()[1:6]  # [2020.0, 5000.0, 6010.0, 6017.0, 6020.0]
y_values = datag.iloc[:, 1].tolist()[1:6]  # Your decimal values

# Create the bar trace
trace1 = go.Bar(
    x=[str(x) for x in x_values],  # Convert to strings to preserve exact labels (optional)
    y=y_values,
    name='Data Series',  # Name for legend (useful if adding multiple traces)
    marker=dict(
        color='rgb(55, 83, 109)'  # Custom bar color (adjust to your preference)
    ),
    hoverinfo='x+y'  # Show both x and y values when hovering over bars
)

# Assemble the figure with layout
data = [trace1]
layout = go.Layout(
    title='Your Bar Chart Title',
    xaxis=dict(
        title='X-axis Category Label',
        tickangle=-45  # Rotate x-labels to prevent overlap
    ),
    yaxis=dict(
        title='Y-axis Value Label',
        tickformat='.4f'  # Show 4 decimal places for clarity
    ),
    margin=dict(l=60, r=40, t=60, b=80)  # Adjust margins to fit all labels
)

fig = go.Figure(data=data, layout=layout)

# Render the chart (opens in your default browser)
offline.plot(fig, filename='custom-bar-chart.html')

# If using Jupyter Notebook, replace the line above with:
# offline.iplot(fig)

Key Improvements & Customization Tips:

  • Replaced deprecated .ix: .iloc is the modern, reliable way to do positional indexing in pandas, avoiding future compatibility issues.
  • Clear data separation: Extracting x_values and y_values explicitly makes the code easier to read and debug.
  • User-friendly tweaks:
    • Rotated x-axis labels to prevent crowding
    • Formatted y-axis ticks to display decimal places clearly
    • Added custom bar color and hover information for better interactivity
    • Adjusted margins to ensure all labels are visible
  • Offline support: No Plotly cloud account required—generates a standalone HTML file or displays directly in Jupyter.

If you want to add more data series, just create a trace2 object and add it to the data list. You can also tweak colors, titles, and axis settings to match your specific use case!

内容的提问来源于stack exchange,提问作者maniA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:15:06