matplotlib中的RC变量未在网页应用的图形和坐标轴中生效

1 投票
1 回答
735 浏览
提问于 2025-04-16 10:11

我正在尝试在一个网页应用中设置matplotlib的线条宽度,这个应用会生成图表。

matplotlib.rc('lines', linewidth=0.5)

在交互模式下使用matplotlib时,这个设置效果很好,但在我的网页应用中却没有任何作用。现在我只能在每次调用时单独提供线条宽度的参数,也就是说:

vals = map(itemgetter(1), sorted(series1.items(), reverse=True))
group1_rects = ax.barh(ind, vals, width, color='r', snap=True, linewidth=0.5)
vals = map(itemgetter(1), sorted(series2.items(), reverse=True))
group2_rects = ax.barh(ind+width, vals, width, color='b', linewidth=0.5)

有没有什么技巧可以让matplotlib.rc在网页应用中生效呢?

我用来获取绘图的图形的代码大致是这样的:

@contextmanager
def render_plot(w=8,h=8):
    fig = Figure(figsize=(w,h))           
    canvas = FigureCanvas(fig)
    response.content_type = 'image/png'
    #Here is where I hope to put RC settings
    matplotlib.rc('lines', linewidth=0.5)
    yield fig
    s = StringIO()
    canvas.print_figure(s)
    response.content = s.getvalue()

1 个回答

1

你发的内容应该是可以正常工作的。作为参考,下面的代码在我使用的python 2.6和matplotlib 1.0中运行得非常好。

from contextlib import contextmanager

import matplotlib as mpl
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

@contextmanager
def render_plot(w=8,h=8):
    fig = Figure(figsize=(w,h))           
    canvas = FigureCanvas(fig)
    mpl.rc('lines', linewidth=5)
    yield fig
    s = file('temp.png', 'w')
    canvas.print_figure(s)

with render_plot() as fig:
    ax = fig.add_subplot(111)
    ax.plot(range(10))

alt text

这个例子在你的系统上能正常运行吗?

撰写回答