Python ❤️ ECharts = pyecharts - comprehensive data visualization toolkit built on Apache ECharts
—
Helper utilities for JavaScript code injection, geographic data management, custom chart extensions, and advanced functionality. These tools enable customization beyond the standard API and integration with external data sources.
Inject custom JavaScript code into charts for advanced functionality and customization.
class JsCode:
def __init__(self, js_code):
"""
JavaScript code wrapper for custom functionality.
Args:
js_code (str): JavaScript code string
"""
def replace(self, pattern, repl):
"""
Replace patterns in JavaScript code using regex.
Args:
pattern (str): Regular expression pattern
repl (str): Replacement string
Returns:
JsCode: Self for method chaining
"""Usage Examples:
from pyecharts.commons.utils import JsCode
from pyecharts.charts import Bar
from pyecharts import options as opts
# Custom formatter function
custom_formatter = JsCode("""
function(params) {
return params.name + ': ' + params.value + '%';
}
""")
# Custom tooltip formatter
tooltip_formatter = JsCode("""
function(params) {
var result = params[0].name + '<br/>';
params.forEach(function(item) {
result += item.marker + item.seriesName + ': ' + item.value + '<br/>';
});
return result;
}
""")
# Apply to chart
bar = (
Bar()
.add_xaxis(["A", "B", "C"])
.add_yaxis("Series", [10, 20, 30])
.set_global_opts(
tooltip_opts=opts.TooltipOpts(formatter=tooltip_formatter),
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter=custom_formatter))
)
)
# Custom color function
color_function = JsCode("""
function(params) {
var colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57'];
return colors[params.dataIndex % colors.length];
}
""")
# Apply dynamic coloring
bar.set_series_opts(itemstyle_opts=opts.ItemStyleOpts(color=color_function))Specialized data structures for chart data management.
class OrderedSet:
def __init__(self, *args):
"""
Ordered set data structure preserving insertion order.
Args:
*args: Initial items to add
"""
def add(self, *items):
"""
Add items to the ordered set.
Args:
*items: Items to add (duplicates ignored)
"""Usage Example:
from pyecharts.commons.utils import OrderedSet
# Create ordered set for category management
categories = OrderedSet("Q1", "Q2", "Q3", "Q4")
categories.add("Q1", "Q5") # Q1 already exists, only Q5 added
print(categories.items) # ["Q1", "Q2", "Q3", "Q4", "Q5"]Built-in geographic data and custom registration functions.
# Geographic data dictionaries (from pyecharts.datasets)
FILENAMES # FuzzyDict: Map filename mappings
COORDINATES # FuzzyDict: City coordinate mappings
EXTRA # dict: Additional geographic data registry
def register_url(asset_url):
"""
Register external map asset URLs.
Args:
asset_url (str): Base URL for map assets
Raises:
Exception: If URL is invalid or registry cannot be loaded
"""
def register_files(asset_files):
"""
Register custom map files.
Args:
asset_files (dict): Mapping of region names to filenames
"""
def register_coords(coords):
"""
Register custom coordinates.
Args:
coords (dict): Mapping of location names to [longitude, latitude] pairs
"""Usage Examples:
from pyecharts.datasets import register_coords, register_files, COORDINATES, FILENAMES
# Register custom coordinates
custom_locations = {
"Custom City": [116.46, 39.92],
"Another Place": [121.48, 31.22],
"Special Zone": [113.23, 23.16]
}
register_coords(custom_locations)
# Register custom map files
custom_maps = {
"custom_region": "path/to/custom_map.js",
"special_area": "path/to/special_area.json"
}
register_files(custom_maps)
# Register external map assets
register_url("https://cdn.example.com/maps/")
# Access built-in data with fuzzy matching
print(COORDINATES["Beijing"]) # Returns coordinates for Beijing
print(FILENAMES["china"]) # Returns filename for China map
# Fuzzy matching for typos
print(COORDINATES["Biejing"]) # Still finds Beijing coordinates
print(FILENAMES["cina"]) # Still finds China mapDictionary with fuzzy string matching capabilities for geographic data.
class FuzzyDict(dict):
def __init__(self, cutoff=0.6):
"""
Dictionary that performs fuzzy lookup for keys.
Args:
cutoff (float): Match ratio threshold (0-1)
"""
def __contains__(self, item):
"""Check if item exists with fuzzy matching."""
def __getitem__(self, lookfor):
"""Get item with fuzzy key matching."""Usage Example:
from pyecharts.datasets import FuzzyDict
# Create fuzzy dictionary
city_data = FuzzyDict(cutoff=0.7)
city_data.update({
"Beijing": [116.46, 39.92],
"Shanghai": [121.48, 31.22],
"Guangzhou": [113.23, 23.16]
})
# Fuzzy lookups work with typos
print(city_data["Biejing"]) # Finds Beijing
print(city_data["Shangai"]) # Finds Shanghai
print(city_data["Guangzou"]) # Finds Guangzhou
# Check membership with fuzzy matching
print("Bejing" in city_data) # True (fuzzy match)JavaScript dependency and asset management functions.
def produce_require_dict(js_dependencies, js_host):
"""
Generate require.js configuration for JavaScript dependencies.
Args:
js_dependencies (list): List of JavaScript file dependencies
js_host (str): Host URL for JavaScript files
Returns:
dict: require.js configuration dictionary
"""Usage Example:
from pyecharts.commons.utils import produce_require_dict
# Generate require.js config
dependencies = ["echarts", "echarts-gl", "echarts-wordcloud"]
host = "https://cdn.jsdelivr.net/npm/"
config = produce_require_dict(dependencies, host)
print(config)
# Returns require.js paths configurationCreate custom chart types and extend existing functionality.
# Example: Custom gauge chart with additional features
from pyecharts.charts import Gauge
from pyecharts import options as opts
from pyecharts.commons.utils import JsCode
class AdvancedGauge(Gauge):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def add_multi_pointer(self, data_pairs, **kwargs):
"""Add multiple pointers to gauge chart."""
# Custom implementation
return self.add("", data_pairs, **kwargs)
def set_gradient_colors(self, colors):
"""Apply gradient colors to gauge."""
gradient_js = JsCode(f"""
new echarts.graphic.LinearGradient(0, 0, 0, 1, {colors})
""")
return self.set_series_opts(
itemstyle_opts=opts.ItemStyleOpts(color=gradient_js)
)
# Usage
gauge = (
AdvancedGauge()
.add_multi_pointer([("CPU", 75), ("Memory", 60)])
.set_gradient_colors([
{"offset": 0, "color": "#00ff00"},
{"offset": 0.5, "color": "#ffff00"},
{"offset": 1, "color": "#ff0000"}
])
)Helper functions for data preparation and transformation.
# Example utility functions (implementation would be in user code)
def prepare_time_series(data, date_column, value_column):
"""
Prepare time series data for line charts.
Args:
data (DataFrame): Input data
date_column (str): Date column name
value_column (str): Value column name
Returns:
tuple: (dates, values) formatted for pyecharts
"""
dates = data[date_column].dt.strftime('%Y-%m-%d').tolist()
values = data[value_column].tolist()
return dates, values
def aggregate_categorical_data(data, category_column, value_column, agg_func='sum'):
"""
Aggregate categorical data for bar/pie charts.
Args:
data (DataFrame): Input data
category_column (str): Category column name
value_column (str): Value column name
agg_func (str): Aggregation function
Returns:
tuple: (categories, values) formatted for pyecharts
"""
grouped = data.groupby(category_column)[value_column].agg(agg_func)
return grouped.index.tolist(), grouped.values.tolist()
def create_heatmap_data(data, x_column, y_column, value_column):
"""
Create heatmap data from tabular format.
Args:
data (DataFrame): Input data
x_column (str): X-axis column name
y_column (str): Y-axis column name
value_column (str): Value column name
Returns:
list: Heatmap data in [x_index, y_index, value] format
"""
x_categories = sorted(data[x_column].unique())
y_categories = sorted(data[y_column].unique())
heatmap_data = []
for _, row in data.iterrows():
x_idx = x_categories.index(row[x_column])
y_idx = y_categories.index(row[y_column])
heatmap_data.append([x_idx, y_idx, row[value_column]])
return heatmap_data, x_categories, y_categoriesCustom theme creation and advanced styling functions.
# Example: Custom theme creation
def create_custom_theme(primary_color="#1f77b4", background_color="#ffffff"):
"""
Create custom color theme for charts.
Args:
primary_color (str): Primary color hex code
background_color (str): Background color hex code
Returns:
dict: Custom theme configuration
"""
return {
"color": [primary_color, "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"],
"backgroundColor": background_color,
"textStyle": {"color": "#333333"},
"title": {"textStyle": {"color": "#333333"}},
"line": {"itemStyle": {"borderWidth": 2}},
"pie": {"itemStyle": {"borderWidth": 1, "borderColor": "#ffffff"}},
"bar": {"itemStyle": {"barBorderWidth": 0.5, "barBorderColor": "#ffffff"}}
}
# Apply custom theme
from pyecharts.charts import Bar
from pyecharts import options as opts
custom_theme = create_custom_theme("#e74c3c", "#f8f9fa")
bar = Bar(init_opts=opts.InitOpts(theme=custom_theme))Utilities for integrating with external libraries and data sources.
# Example: Pandas integration helpers
def from_pandas_dataframe(df, x_column, y_columns, chart_type="bar"):
"""
Create chart directly from pandas DataFrame.
Args:
df (DataFrame): Source data
x_column (str): X-axis column name
y_columns (list): Y-axis column names
chart_type (str): Chart type to create
Returns:
Chart: Configured chart instance
"""
from pyecharts.charts import Bar, Line, Scatter
chart_classes = {
"bar": Bar,
"line": Line,
"scatter": Scatter
}
chart = chart_classes[chart_type]()
chart.add_xaxis(df[x_column].tolist())
for column in y_columns:
chart.add_yaxis(column, df[column].tolist())
return chart
# NumPy integration
def from_numpy_arrays(x_data, y_data, chart_type="line"):
"""
Create chart from NumPy arrays.
Args:
x_data (ndarray): X-axis data
y_data (ndarray): Y-axis data
chart_type (str): Chart type to create
Returns:
Chart: Configured chart instance
"""
from pyecharts.charts import Line, Scatter
chart_classes = {"line": Line, "scatter": Scatter}
chart = chart_classes[chart_type]()
chart.add_xaxis(x_data.tolist())
chart.add_yaxis("Series", y_data.tolist())
return chartTools for debugging charts and development workflow.
# Example development utilities
def debug_chart_options(chart):
"""
Print chart configuration for debugging.
Args:
chart: Chart instance to debug
"""
import json
options = chart.dump_options()
print(json.dumps(json.loads(options), indent=2))
def validate_chart_data(chart):
"""
Validate chart has proper data structure.
Args:
chart: Chart instance to validate
Returns:
list: List of validation errors
"""
errors = []
options = json.loads(chart.dump_options())
if not options.get("series"):
errors.append("Chart has no data series")
for i, series in enumerate(options.get("series", [])):
if not series.get("data"):
errors.append(f"Series {i} has no data")
return errors
def chart_performance_profile(chart, output_path="profile.html"):
"""
Generate performance profile for chart rendering.
Args:
chart: Chart instance to profile
output_path (str): Output file path
"""
import time
start_time = time.time()
html_content = chart.render_embed()
render_time = time.time() - start_time
data_size = len(json.loads(chart.dump_options()).get("series", []))
profile_info = f"""
Render Time: {render_time:.3f}s
Data Series: {data_size}
HTML Size: {len(html_content)} characters
"""
print(profile_info)
return profile_infoInstall with Tessl CLI
npx tessl i tessl/pypi-pyecharts