Python development [module]: Pygal to draw a histogram, pythonpygal
Pygal
Pygal can be used to generate a Scalable Vector Graphics file. It is useful for charts that need to be displayed on different screens. It can be scaled automatically to adapt to the viewer's screen.
1. Install the Pygal Module
① Windows
# Install the Pygal module $ pip3 install pygal
② Linux and OS X systems
# Install the Pygal module $ pip install -- user pygal = 1.7
2. Pygal gallery-Histogram
Simulate the dice, analyze the final result, and generate the image
Create a die. py sieve file:
From random import randintclass Die (): ''' class for throwing dice ''' def _ init _ (self, num_sides = 6): self. num_sides = num_sides # Number of dice def roll (self): return randint (1, self. num_sides)
Create the die_visual.py file and generate a histogram:
From die import Dieimport pygaldie = Die () # Data Set results = [] count = 1for roll_num in iter (lambda * args: die. roll (), None): results. append (roll_num) if count> = 1000: break count + = 1 # analysis result frequencies = [] for value in range (1, die. num_sides + 1): frequencie = results. count (value) frequencies. append (frequencie) # visualize the result hist = pygal. bar () # generate an instance hist. title = 'results' of rolling one D6 1000 times '# title hist. x_labels = ['1', '2', '3', '4', '5', '6'] # X axis Numerical Coordinate hist. x_title = 'result' # X axis title hist. y_title = 'frequency of result' # Y axis title hist. add ('d6 ', frequencies) # input the Y axis data hist. render_to_file ('Die _ visual. svg ') # file generation path, which must be an svg file
Open the die_visual.svg file in a browser:
3. Throw two dice at the same time
Modify the die_visual.py file:
From die import Dieimport pygaldie1 = Die () die2 = Die () # Data Set results = [] for I in range (5000): result = die1.roll () + die2.roll () results. append (result) # analysis result frequencies = [] for value in range (2, die1.num _ sides + die2.num _ sides + 1): frequencie = results. count (value) frequencies. append (frequencie) # visualize the result hist = pygal. bar () # generate an instance hist. title = 'results' of rolling one D6 5000 times '# title hist. x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10 ', 11,12] # X axis Numerical Coordinate hist. x_title = 'result' # X axis title hist. y_title = 'frequency of result' # Y axis title hist. add ('d6 + D6 ', frequencies) # input the Y axis data hist. render_to_file ('Die _ visual. svg ') # file generation path, which must be an svg file
Browser browsing image die_visual.svg: