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

如何在PyX密度图样式中生成水平颜色轴?

PyX中把密度图颜色条改为水平放置的解决方法

直接通过手动创建水平颜色条并调整布局位置即可解决,不需要复杂操作,具体步骤和代码示例如下:

核心思路

  1. 生成密度图时禁用自动添加的垂直颜色条
  2. 手动创建水平方向的颜色条,关联密度图的颜色映射
  3. 使用画布(canvas)将颜色条放置在主图上方,调整两者的位置间距

完整代码示例

import math
from pyx import *
from pyx.graph import graph, density, colorbar

# 生成曼德博集合数据(可替换为你的密度数据)
def mandelbrot(c, max_iter):
    z = 0
    for n in range(max_iter):
        if abs(z) > 2:
            return n
        z = z*z + c
    return max_iter

width, height = 200, 200
xmin, xmax = -2, 1
ymin, ymax = -1.5, 1.5
max_iter = 100

data = []
for y in range(height):
    y_val = ymin + (ymax - ymin) * y / (height-1)
    row = []
    for x in range(width):
        x_val = xmin + (xmax - xmin) * x / (width-1)
        row.append(mandelbrot(complex(x_val, y_val), max_iter))
    data.append(row)

# 创建密度图,不自动生成垂直颜色条
g = graph.graphxy(width=8, height=8,
                  x=graph.axis.lin(min=xmin, max=xmax),
                  y=graph.axis.lin(min=ymin, max=ymax))
d = density.density(data, xmin, xmax, ymin, ymax,
                    colormap=color.rgb.colormap.Blues)
g.plot(d)

# 创建水平颜色条,匹配主图宽度,设置高度
cb = colorbar.ColorBar(d, direction="horizontal", width=8, height=0.5)

# 组合布局:颜色条放在主图上方,调整间距
c = canvas.canvas()
# 通过translate控制颜色条的垂直位置,ymax+0.2是主图顶部上方0.2单位的位置
c.draw(cb, [trafo.translate(0, ymax + 0.2)])
c.draw(g)

# 输出文件
c.writeEPSfile("mandelbrot_horizontal_cb")
c.writePDFfile("mandelbrot_horizontal_cb")

关键细节说明

  • direction="horizontal":指定颜色条为水平方向
  • 颜色条的width设置为和主图一致(示例中都是8),保证整体宽度统一,避免页面缩放问题
  • 通过trafo.translate(0, ymax + 0.2)调整颜色条的垂直位置,0.2是颜色条和主图之间的间距,可按需修改
  • 如果需要自定义颜色条的刻度、标签样式,可以给ColorBar添加axisattrs参数,比如:
    cb = colorbar.ColorBar(d, direction="horizontal", width=8, height=0.5,
                           axisattrs=[graph.axis.tick(ticklen=0.1),
                                      graph.axis.label(r"迭代次数")])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:45:55