【问题标题】:python: plotting a line defining the color by a functionpython:绘制一条通过函数定义颜色的线
【发布时间】:2013-08-12 00:01:55
【问题描述】:

我想在 python 中绘制一个向量,根据函数的值定义其颜色(类似于y=f(x))。例如,如果线条有一个单位长度,我想在开头 (x=0) 用蓝色填充它,在结尾 (x=1) 用红色填充,使用函数定义调色板。

我尝试查看网络,但没有任何结果。

谁能帮帮我?

提前致谢。

【问题讨论】:

  • 请细化这个问题 - 是关于根据特定绘图库的值设置颜色,还是关于使用 python 绘图的一般问题

标签: python plot


【解决方案1】:

您可能需要为此使用 Python PIL:http://effbot.org/imagingbook/pil-index.htm

安装 PIL 后,这是一个简单的示例,可以帮助您入门:

import Image, ImageDraw
import math

# Create image, giving size and background color
im = Image.new("RGB", (400,400), (0, 128, 128) )

# You will do your drawing in the image through the 'draw' object
draw = ImageDraw.Draw(im)


def f(x):
    return math.sin(3*x)

# One loop alongside the line
for i in xrange( 400 ):
    # and another if you need a different width
    for j in xrange( 196, 204 ):

        # Calculate an x-value in the range 0-1. This is a hack
        # you might need something more general.
        x = i / 400.0


        c = f(x)

        # And calculate the colors from there
        red = int( 256*(1.0-c) ) 
        blue = 256 - red

    im.putpixel( ( i, j ), (red, 0, blue) )

im.save("test.png", "PNG")

当然,对于任何需要性能的东西,我不会推荐上述方法,但它可能足以让您摆脱匆忙。

【讨论】:

    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 2019-05-25
    • 2018-11-16
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多