简体   繁体   English

如何更改pyGal折线图上绘制点的颜色

[英]How to change color of drawn points on pyGal line chart

I am creating a line graph using pygal by passing in an array of numbers to be graphed. 我通过传入要绘制的数字数组来创建使用pygal的折线图。 I am wishing for the points marked on the graph to change color when they are in/outside of a certain range. 我希望图表上标记的点在一定范围之内/之外时会改变颜色。 Ie If there is a point logged over 40, color it red, if there is a point logged under 20, color it blue. 即,如果记录的点超过40,则将其着色为红色,如果记录的点低于20,则将其着色为蓝色。

There does not seem to be an easy way to loop through the array and draw a single point. 似乎没有一种简单的方法可以遍历数组并绘制单个点。

The graph is being made with the following code: 该图使用以下代码制作:

    customStyle = Style(colors=["#000000"])
    chart = pygal.Line(style=customStyle)
    chart.title = 'Browser usage evolution (in %)'
    chart.x_labels = recordedDates
    chart.add('Humidity', recordedHumidity)
    chart.render_to_png("out.png")

I would like to have all points above 40 red and below 20 blue. 我希望所有点都高于40红色和低于20蓝色。

You can replace a number in the array with a dict that tells Pygal how to render the data point. 您可以用告诉Pygal如何呈现数据点的dict替换数组中的数字。 This dict must contain the key value , which is the number you would have passed, alongside any customisation options you want to use. dict必须包含的关键value ,这是你会通过数量,沿着你想使用的任何自定义选项。 The list of available options is provided on the value configuration page of the docs , but the one you need here is color . 可用选项的列表在文档的值配置页面上提供,但是您需要的是color

You can simply iterate over your existing array, creating a dictionary where color is set appropriately for the value: 您可以简单地遍历现有数组,创建一个字典,在其中为该值适当设置color

data = []
for v in recordedHumidity:
    if v > 40:
        data.append({"value": v, "color": "red"})
    elif v < 20:
        data.append({"value": v, "color": "blue"})
    else:
        data.append(v)

You can then pass the newly created array when adding the series: 然后,您可以在添加序列时传递新创建的数组:

customStyle = Style(colors=["#000000"])
chart = pygal.Line(style=customStyle)
chart.x_labels = recordedDates
chart.add('Humidity', data)
chart.render_to_png("out.png")

带有不同色点的示例图表

You might also want to look at the chart configuration and series configuration pages in the docs to see how to customise other aspects of the chart, such as the size of the markers. 您可能还希望查看文档中的图表配置系列配置页面,以了解如何自定义图表的其他方面,例如标记的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM