Install pygal
In Windows, the command is similar to the following:
pyhton -m pip install --user pygal==1.7
Draw a histogram
1. To create a bar chart, we create an instance of pygal.Bar() and store it in the picture.
picture=pygal.Bar()
2. Next, set the title attribute to represent the name of the histogram, and use all possible results of the dice roll as the label of the x-axis (the label must be string type, int type will report an error).
xlabels=list(range(1,sides+1))
picture.x_labels=[]
for x in xlabels:
picture.x_labels.append(str(x))
3. Use add() to add a series of values to the chart ('Die' is a label assigned to the added value, which can be set at will, but it is indispensable; frequents is a list that stores the values that will appear in the chart).
picture.add('Die',frequencies)
4. Render the picture as an SVG file. The extension of this file must be .svg.
picture.render_to_file('die_visual.svg')
Result demonstration:
import pygal
from random import randint
class Die():
def __init__(self,sides=6):
self.sides=sides
def roll(self):
return randint(1,self.sides)
values=[]
sides=int(input("How many sides? "))
die_visual=Die(sides)
for roll_num in range(20):
value=die_visual.roll()
values.append(value)
frequencies=[]
for value in range(1,int(sides)+1):
frequency=values.count(value)
frequencies.append(frequency)
picture=pygal.Bar()
picture.title='Frequencies of '+str(sides)+' kinds of situation'
picture.x_title='Values'
picture.y_title='Frequency of Values'
xlabels=list(range(1,sides+1))
picture.x_labels=[]
for x in xlabels:
picture.x_labels.append(str(x))
picture.add('Die',frequencies)
picture.render_to_file('die_visual.svg')