How to change color of drawn points on pyGal line chart

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

I am creating a line graph using pygal by passing in an array of numbers to be graphed. I am wishing for the points marked on the graph to change color when they are in/outside of a certain range. I.e. If there is a point logged over 40, color it red, if there is a point logged under 20, color it blue.

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">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.

profilepic.png
manpreet 2 years ago

You can replace a number in the array with a dict that tells Pygal how to render the data point. This dict must contain the key value, which is the number you would have passed, alongside any customisation options you want to use. The list of available options is provided on the value configuration page of the docs, but the one you need here is color.

You can simply iterate over your existing array, creating a dictionary where color is set appropriately for the value:

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")

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.