In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the Matplotlib bar chart drawing method has what related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that you will have something to gain after reading this Matplotlib bar chart method, let's take a look at it.
Import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import font_manager I. General bar chart
The general bar chart is drawn using the pyplot.bar () function, and its form and parameters are as follows:
The main parameters of matplotlib.pyplot.bar (x, height, width=0.8, bottom=None, *, align='center', data=None, * * kwargs) explain: # x: an array or list that represents the coordinate points of the x-axis of the bar chart to be drawn. # height: an array or list that represents the coordinate points on the y-axis of the bar chart to be drawn. # width: the width of each bar chart is 0.8 by default. The baseline of # bottom:y axis is 0 by default, that is, 0 # align from the bottom: alignment, {'center','edge'}, default is center, center alignment; edge is aligned by side, right or left, depending on the positive or negative of width. # color: color of the bar chart. # edgecolor: the color of the bar border. # linewidth: the width of the bar chart border. If 0, the border example is not drawn:
One day the movie box office data:
Movies = {wandering Earth: 40.78, Flying Life: 15.77, Crazy Aliens: 20.83, King of New Comedy: 6.10, Clean Government: 1.10, Pu Songling: 1.49, Pig Peiqi's Lunar New year: 1.22, Bear haunting the primitive Age: 6.71)
Directly by getting the key value of the dictionary as the x _ quotation y-axis data
# box office unit: 100 million yuan movies = {"wandering Earth": 40.78, "Flying Life": 15.77, "Crazy Aliens": 20.83, "King of the New Comedy": 6.10, "Clean Government": 1.10, "Pu Songling": 1.49, "Pig Peiqi over the New year": 1.22 "Bear haunts the primitive Age": 6.71} # Chinese display problem plt.rcParams ['font.sans-serif'] = [' SimHei'] plt.rcParams ['axes.unicode_minus'] = Falseplt.rcParams [' font.size'] = 1 "set the size of the graph plt.figure (figsize= (15Finals 8)) x = list (movies.keys ()) # get x-axis data (dictionary key) y = list (movies.values ()) # get y-axis data (dictionary value) plt.bar (x The title plt.title ("movie box office data", size=26) # sets the axis label plt.xlabel ("movie name", size=28) plt.ylabel ("box office / 100 million", size=28) plt.show ()
You can also use a dictionary to create a DataFrame index, which is passed in through the data parameter
# box office unit: 100 million yuan movies = {"wandering Earth": 40.78, "Flying Life": 15.77, "Crazy Aliens": 20.83, "King of the New Comedy": 6.10, "Clean Government": 1.10, "Pu Songling": 1.49, "Pig Peiqi over the New year": 1.22 Movies_df = pd.DataFrame (data= {"name": list (movies.keys ()), "tickes": list (movies.values ())}) # create DataFrame index through dictionary font = font_manager.FontProperties (fname='C:\ Windows\ Fonts\ STSONG.TTF',size=12) # use font_manager module to set Chinese # set the size of the diagram Pass in xname yplt.figure (figsize= (14jie 5)) # use plt.bar () to draw a bar graph plt.bar ("name", "tickes", data=movies_df,width=0.5,bottom=0,align='edge',color='g',edgecolor = 'ringing line widthpieces 2) # to set the X-axis scale Set font, you can also set font size sizeplt.xticks (fontproperties=font) # set title plt.title ("Cinema Box data", size=30) # set X Magi Y-axis name plt.ylabel ('box office', fontproperties=font,size=25) plt.xlabel ('movie name', fontproperties=font,size=25) # set Y scale plt.yticks (range (0Mague 50), ["% d"% x for x in range (050)], fontproperties=font1,size=20) # keep only graphic information plt.show ()
2. Horizontal bar chart
The horizontal bar needs to use barh (), which is very similar to bar, except that it rotates the direction. The parameter is also similar to pyplot.bar ()
Matplotlib.pyplot.barh (y, width, height=0.8, left=None, *, align='center', * * kwargs) # main parameters explain: # y: an array or list that represents the coordinate points on the y axis of the bar chart to be drawn. # width: an array or list that represents the value (that is, the length) of the bar graph to be drawn on the x-axis. # height: the height (width) of the bar chart. Default is 0.8. # left: the baseline of the bar chart, that is, the distance from the y-axis. The default is 0 example:
Plt.barh ()
Movies = {wandering Earth: 40.78, Flying Life: 15.77, Crazy Aliens: 20.83, King of New Comedy: 6.10, Clean Government: 1.10, Pu Songling: 1.49, Pig Peiqi during the New year: 1.22 Font2 = font_manager.FontProperties (fname='C:\ Windows\ Fonts\ STSONG.TTF') x1 = list (movies.keys ()) y1 = list (movies.values ()) # set the size of the graph plt.figure (figsize= (10Power5)) # set the Y-axis scale using plt.barh () plt.barh Set the font, you can also set the font size sizeplt.yticks (fontproperties=font2,size=20) plt.xlabel ("box office / 100 million", size=20) # set the title plt.title ("movie box office data", size=30) # keep only the graphic information plt.show ()
Axes.barh (y, width, height=0.8, left=None, *, align='center', * * kwargs)
In addition, graphics can be drawn through the returned axes object
Movies = {wandering Earth: 40.78, Flying Life: 15.77, Crazy Aliens: 20.83, King of New Comedy: 6.10, Clean Government: 1.10, Pu Songling: 1.49, Pig Peiqi during the New year: 1.22 Font2 = font_manager.FontProperties (fname='C:\ Windows\ Fonts\ STSONG.TTF') mdf = pd.DataFrame (data= {"name": list (movies.keys ()), "tickes": list (movies.values ())}) fig,axes = plt.subplots () # drawing axes.barh ("name", "tickes", data= mdf,height=0.6,left=0,color='c') through the returned axes object Edgecolor='r') # set the Y-axis scale Set the font, you can also set the font size sizeplt.yticks (fontproperties=font2,size=20) plt.xlabel ("box office / 100 million", size=24) # set the title plt.title ("movie box office data", size=27) # keep only the graphic information plt.show ()
Third, the drawing of grouping bar chart
Five-day movie box office data (assuming dates are 1.1-1.5): and converted to DataFrame index
Movies = {"wandering Earth": [2.01pr 4.59pr 7.99pr 11.83pr 16], "Flying Life": [3.19pr 5.08pr 6.73pr 8.10g 9.35], "Crazy Aliens": [4.07pr 6.92pr 9.30pr 11.29pr 13.03], "King of New Comedy": [2.72pr 3.79pr 4.45pr 4.83jue 5.11], "Clean Government Wind and Cloud": [0.56pr 0.74pr 0.83mer 0.92] "Detective Pu Songling": [0.66, 0.95, 1.10, 1.17, 1.23], "Pig Pei Qi, over the New year": [0.58, 0.81, 0.91, 1.01, 1.07], "the primitive age of bears": [1.13, 1.96, 2.73, 3.42, 4.05]} mdf = pd.DataFrame (movies) mdf.
The idea of drawing a grouped bar chart: first select the box office data of all the movies every day, which can be obtained by using the DataFrame.iloc [] method, such as
# get first day box office data mdf.iloc [0] Rangers Earth 2.01 Flying Life 3.19 Crazy Aliens 4.07 New Comedy King 2.72 incorruptible Government 0.56 Pu Songling 0.66 Pig Pei Qi passes the Lunar New year 0.58 bears haunt the primitive era 1.13Name: 0, dtype: float64
Then draw by day, here you need to determine a center point as the bar chart location of the intermediate date (here is the third day), how many movies need as many center points, you can use np.arange (len (movies)) to get the x-axis scale as the center point. Finally, the position of the bar chart can be adjusted according to the width of the bar chart according to the date.
Plt.figure (figsize= (15 Fonts 5)) # set the X axis scale to an array (with broadcast function) xticks = np.arange (len (movies)) # set font font = font_manager.FontProperties (fname='C:\ Windows\ Fonts\ STSONG.TTF') # set bar width bar_width = 0.1 set the position of all movie bars on the first day plt.bar (xticks-2*bar_width,mdf.iloc [0], width=bar_width Color='pink') # iloc [] take a line from DataFrame # set the location of all movie bars on the second day plt.bar (xticks-bar_width,mdf.iloc [1], width=bar_width) # set the location of all movie bars on the third day By default, plt.bar (xticks,mdf.iloc [2], width=bar_width) # sets the location of all movie bars on the fourth day plt.bar (xticks+bar_width,mdf.iloc [3], width=bar_width) # sets the location of all movie bars on the fifth day plt.bar (xticks+2*bar_width,mdf.iloc [4], width=bar_width) # sets the X-axis information plt.xticks (xticks,mdf.columns,fontproperties=font) Size=15) # set the Y scale plt.yticks (range (0Magne20Magne2), [% d "% x for x in range (0Magne20p2)], fontproperties=font,size=16) # set the name of the Y axis plt.ylabel ('box office / 100 million', fontproperties=font,size=30) plt.xlabel ('name of the movie', fontproperties=font,size=30) # set the title plt.title (" five days box office data ", fontproperties=font,size=30) # keep only graphic information plt.show ()
Use loops to draw daily data
Plt.figure (figsize= (16pyr5)) # sets the X-axis scale to an array (with broadcast function) # xticks1 = np.arange (len (movies)) # so that the distance between each movie's X-axis is 1. If the width of 5 bars is greater than 1 and overlaps with other movies, you can set the step size xticks1 = np.arange (0LN (movies), 7) # change the step size To change the first parameter of xticks (step * ticks labels) at the setting of the X-axis information Otherwise, it will not correspond to # set font font4 = font_manager.FontProperties (fname='C:\ Windows\ Fonts\ STSONG.TTF') # set bar width bar_width2 = 1.0 "use cycle to draw the bar chart of the first five days for index in mdf.index: # plt.bar (xticks1+ (- 2+index) * bar_width2,mdf.iloc [index], width=bar_width2 Label='% d box office'% (index+1)) xs = xticks1+ (- 2+index) * bar_width2 # location on the X axis day_tickets = mdf.iloc [index] plt.bar (xs,day_tickets,width=bar_width*7,label= "d day box office"% (index+1)) # set comment text # zip (day_tickets,xs) packaged as a list of elements as tuples The number of elements coincides with the shortest list for ticket,x in zip (day_tickets,xs): # ticket is the value of the day_tickets list X is the value of xs plt.annotate (ticket,xy= (xjimin ticket), xytext= (xray 0.2 ticketmakers 0.1) # set the X axis information plt.xticks (7 days xticks dint mdf.columnsPhontpropertiespowerfont4) # set the name of the Y axis plt.ylabel ('box office / 100 million', fontproperties=font4,size=25) plt.xlabel ('movie name', fontproperties=font4,size=25) # set the title plt.title ("five days box office data", fontproperties=font4) Size=30) # set legend font4.set_size (15) # legend has no size attribute You can change the size in the font setting font4 (or font.set_size (): only change the legend plt.legend (prop=font4) # according to the label tag in the bar () function, indispensable # set grid plt.grid () # retain only graphic information plt.show ()
Fourth, stack bar chart drawing
Stacked bar chart is to draw the graph on the basis of the existing data, using bottom parameters to draw the new data with the existing data as the base of the new data, which can achieve the purpose of adjusting the position of the bar chart.
Example: # Equal score between men and women menMeans = (20,35,30,35,27) womenMeans = (25,32,34,20,25) groupNames = ('G _ 1') G2') xs = np.arange (len (menMeans)) # how many groups font5 = font_manager.FontProperties (fname='C:\ Windows\ Fonts\ STSONG.TTF',size=16) plt.figure (figsize= (15 ~ 7)) # draw male score plt.bar (xs MenMeans,label=' male score', width=0.4) # draw female score Plt.bar based on the maximum male score (xs,womenMeans,bottom=menMeans,label=' female score', width=0.4) # set legend plt.legend (prop=font5) # set according to the label tag in the bar () function # set the X axis scale name plt.xticks (xs,groupNames) # set the label plt.xlabel ("Group", fontproperties=font5,size=23) plt.ylabel ("score", fontproperties=font5 Size=23) # set title plt.title ("scores for different groups of men and women", fontproperties=font5,size=28) # keep only graphics plt.show ()
This is the end of this article on "what are the methods of drawing bar charts in Matplotlib?" Thank you for reading! I believe you all have a certain understanding of the knowledge of "what are the methods of drawing bar charts in Matplotlib". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.