杰瑞科技汇

Python ChartDirector如何快速绘制专业图表?

Of course! Here's a comprehensive guide to using ChartDirector in Python, a powerful and flexible charting library.

Python ChartDirector如何快速绘制专业图表?-图1
(图片来源网络,侵删)

What is ChartDirector?

ChartDirector is a professional charting component that is known for its high performance, extensive customization options, and high-quality output. It's a commercial library, but it offers a very generous free license for non-commercial and academic use.

Key features include:

  • Wide Range of Chart Types: From basic 2D/3D charts (line, bar, pie) to advanced financial, statistical, and scientific charts (Gantt, surface, contour, waterfall).
  • High Performance: Optimized for rendering large amounts of data quickly.
  • Extreme Customization: You have fine-grained control over almost every visual element of the chart.
  • Multi-Purpose Output: Charts can be saved as image files (PNG, JPG, GIF, BMP, SVG), PDFs, or even generated as interactive web charts with tooltips and drill-downs.

Step 1: Installation

First, you need to install the Python package. The package name is pychartdir.

pip install pychartdir

Step 2: Licensing (Important!)

Before you can generate charts, you must register a license. If you are using it for non-commercial or academic purposes, you can get a free license.

Python ChartDirector如何快速绘制专业图表?-图2
(图片来源网络,侵删)
  1. Go to the Chart Licensing Page: https://www.advancedsw.com/chartdirector/licensing.html
  2. Fill out the form to get your free license key. It will be sent to your email.
  3. The license key is a simple string.

You need to register this license once in your application. A common place is at the beginning of your main script.

import pychartdir
# IMPORTANT: Register your license key.
# Replace "YOUR_LICENSE_KEY" with the actual key you received.
pychartdir.license("YOUR_LICENSE_KEY") 

Step 3: Creating Your First Chart (A Simple Line Chart)

Let's break down the process of creating a chart. The core idea is to:

  1. Prepare your data (as lists or arrays).
  2. Create a Chart object, providing the data and chart type.
  3. Configure the chart's appearance (title, axis labels, etc.).
  4. Output the chart (e.g., save it to a file or display it).

Here is a complete, commented example of a simple line chart.

import pychartdir
# --- 1. License Registration ---
# Replace with your actual license key
pychartdir.license("YOUR_LICENSE_KEY")
# --- 2. Data Preparation ---
# Data for the chart
data = [30, 28, 40, 55, 75, 68, 90]
labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# --- 3. Create a Chart Object ---
# We create a XYChart object for line charts, bar charts, etc.
# The constructor takes the width and height of the chart in pixels.
chart = pychartdir.XYChart(600, 400)
# --- 4. Configure the Chart ---
# a. Add a title
chart.addTitle("Weekly Sales Performance", "Arial Bold 20", "#000080")
# b. Add the plot area
# The plot area is where the actual chart (lines, bars) is drawn.
# We set the margins and a light grey background.
chart.setPlotArea(50, 55, 500, 300, 0xf0f0f0, -1, 0xc0c0c0, -1, 0x888888)
# c. Add the data to the chart
# We create a line layer using the Layer object.
layer = chart.addLineLayer()
layer.addDataSet(data, pychartdir.color.DarkRed).setDataSymbol(pychartdir.Shape.Circle, 8)
# This adds a dataset to the layer, sets its color to dark red,
# and sets the data point symbol to a circle of size 8.
# d. Configure the X-Axis
# The X-axis will use our labels.
chart.xAxis().setLabels(labels)
chart.xAxis().setTitle("Day of the Week")
# e. Configure the Y-Axis
# The Y-axis will represent the sales value.
chart.yAxis().setTitle("Sales (in units)")
chart.yAxis().setAxisMin(0) # Start the Y-axis at 0
# --- 5. Output the Chart ---
# Save the chart as a PNG file
chart.makeChart("line_chart.png")
print("Chart saved as line_chart.png")

When you run this script, a file named line_chart.png will be created in your directory. It will look something like this:

Python ChartDirector如何快速绘制专业图表?-图3
(图片来源网络,侵删)

Step 4: Exploring Other Chart Types

ChartDirector makes it easy to switch between chart types. The key is often in the addLayer() method. Let's create a bar chart with the same data.

import pychartdir
# License registration
pychartdir.license("YOUR_LICENSE_KEY")
# Data
data = [30, 28, 40, 55, 75, 68, 90]
labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# Create a new chart
chart = pychartdir.XYChart(600, 400)
# Add title
chart.addTitle("Weekly Sales Performance", "Arial Bold 20", "#000080")
# Add plot area
chart.setPlotArea(50, 55, 500, 300, 0xf0f0f0, -1, 0xc0c0c0, -1, 0x888888)
# --- The main change is here: use addBarLayer ---
layer = chart.addBarLayer(pychartdir.color.DeepSkyBlue)
layer.addDataSet(data)
# Configure axes (same as before)
chart.xAxis().setLabels(labels)
chart.xAxis().setTitle("Day of the Week")
chart.yAxis().setTitle("Sales (in units)")
chart.yAxis().setAxisMin(0)
# Output
chart.makeChart("bar_chart.png")
print("Chart saved as bar_chart.png")

This will produce a bar chart named bar_chart.png.


Step 5: Advanced Customization (Combination Chart)

ChartDirector excels at combining different chart types. Let's create a combination chart with bars and a line.

import pychartdir
import numpy as np
# License registration
pychartdir.license("YOUR_LICENSE_KEY")
# Data
labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
revenue = [2100, 1900, 3000, 5000, 2300, 2900]
profit = [230, 340, 510, 420, -100, -300]
# Create chart
chart = pychartdir.XYChart(600, 400)
chart.addTitle("Monthly Revenue and Profit", "Arial Bold 16")
chart.setPlotArea(50, 60, 500, 280, 0xeeeeee, 0, 0x888888, 0, 0xffffff)
# --- Add the first layer: Bars for Revenue ---
layer1 = chart.addBarLayer(revenue, pychartdir.color.Orange)
layer1.setAggregateStyle(pychartdir.AggregateStyle.Stack) # Optional: stack if you had multiple bar datasets
layer1.setDataLabelFormat("${value}")
# --- Add the second layer: Line for Profit ---
# We need to create a new layer for the line chart
layer2 = chart.addLineLayer(profit, pychartdir.color.DarkGreen)
layer2.setDataSymbol(pychartdir.Shape.Circle, 6)
# Configure axes
chart.xAxis().setLabels(labels)
chart.xAxis().setTitle("Month")
chart.yAxis().setTitle("Amount (USD)")
chart.yAxis().setAxisMin(0) # Ensure Y-axis starts at 0 for the bars
# Output
chart.makeChart("combination_chart.png")
print("Chart saved as combination_chart.png")

This demonstrates how you can add multiple layers to a single chart, each with its own data representation.


Step 6: Output Formats

You are not limited to PNG. The makeChart method supports several formats:

  • Images: makeChart("output.jpg"), makeChart("output.gif"), makeChart("output.bmp"), makeChart("output.svg")
  • PDF: makeChart("output.pdf")
  • HTML with Tooltips (Interactive): This is a great feature for web applications.
    # Create an HTML file containing the chart
    chart.makeChart("interactive_chart.html")

    This will generate an HTML file. When you open it in a browser, you'll see the chart, and hovering over the data points will show tooltips (which you can customize).


Summary and Key Takeaways

  1. Installation: pip install pychartdir
  2. License is Mandatory: Always call pychartdir.license("YOUR_KEY") at the start.
  3. Core Workflow:
    • Prepare data.
    • Create a Chart object (e.g., XYChart).
    • Add a Title and PlotArea.
    • Add Layers (e.g., addLineLayer, addBarLayer) and DataSets to them.
    • Configure xAxis and yAxis.
    • Use makeChart() to save the output.
  4. Customization is King: Use methods like addTitle, setPlotArea, setDataSymbol, and setDataLabelFormat to fine-tune your chart's appearance.
  5. Versatility: It handles simple charts to complex, multi-layered, and interactive charts with ease.

For more detailed examples and the full API reference, the official ChartDirector Python Chart Gallery is the best resource: https://www.advancedsw.com/chartdirector/pythonchart.html

分享:
扫描分享到社交APP
上一篇
下一篇