Python Matplotlib Tutorial - Indian AI Production https://indianaiproduction.com/python-matplotlib-tutorial-mastery-in-matplotlib-library/ Artificial Intelligence Education Free for Everyone Wed, 11 Sep 2019 07:17:39 +0000 en-US hourly 1 https://i0.wp.com/indianaiproduction.com/wp-content/uploads/2019/06/Channel-logo-in-circle-473-x-472-px.png?fit=32%2C32&ssl=1 Python Matplotlib Tutorial - Indian AI Production https://indianaiproduction.com/python-matplotlib-tutorial-mastery-in-matplotlib-library/ 32 32 163118462 Matplotlib imshow – Read & Show image using imread() & plt.imshow() https://indianaiproduction.com/matplotlib-imshow/ https://indianaiproduction.com/matplotlib-imshow/#respond Wed, 31 Jul 2019 11:12:35 +0000 https://indianaiproduction.com/?p=873 If you worry about, how to read and show an image using the matplotlib library then here you will get a solution for your problem. Along with that, you will be got a bonus. The matplotlib imshow() function helps to show the image. But plt.imshow() didn’t work without mpimg.imread() function which is belongs to matplotlib.image …

Matplotlib imshow – Read & Show image using imread() & plt.imshow() Read More »

The post Matplotlib imshow – Read & Show image using imread() & plt.imshow() appeared first on Indian AI Production.

]]>
If you worry about, how to read and show an image using the matplotlib library then here you will get a solution for your problem. Along with that, you will be got a bonus. The matplotlib imshow() function helps to show the image.

But plt.imshow() didn’t work without mpimg.imread() function which is belongs to matplotlib.image module. So lets start practical.

Import Libraries

import matplotlib.pyplot as plt
import matplotlib.image as mpimg # image module for image reading

Reading Image

Here, we use mpimg.imread() method. Which belongs to the matplotlib image module.

img = mpimg.imread("pie_char.png") # give addres of image location
print(img)

Output >>>

[[[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       ...,

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        ...,
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]]], dtype=float32)

Above you can see, when we call img then got numpy array but how. because mpimg.imread() function read pie_char.png image and store in numpy array format.

Get more information about img.

print("Data type of img > ", type(img))
print("Shape of img > ", img.shape)
print("Dimention of img > ",img.ndim)

output >>>

Data type of img > numpy.ndarray

Shape of img > (288, 432, 4)

Dimention of img > 3

Show Image using matplotlib imshow

It’s time to show an image using a read dataset.

To show an image, use plt.imshow() function.

Syntax :plt.imshow(
                                     X,                                     
                                     cmap=None,
                                     norm=None,
                                     aspect=None,
                                     interpolation=None,
                                     alpha=None,
                                     vmin=None,
                                     vmax=None,
                                     origin=None,
                                     extent=None,
                                     shape=None,
                                     filternorm=1,
                                     filterrad=4.0,
                                     imlim=None,
                                     resample=None,
                                     url=None,
                                     *,
                                     data=None,
                                     **kwargs,
                                     )

plt.imshow(img)
plt.show()

Output >>>

Now, removing the axis and increase figure size and then show the same image.

plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(img)
plt.show()

Output >>>

Now, it looks great but can we add it’s a color bar. Yes, using plt.colorbar() function.

Show Image with Colorbar

plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(img)
plt.colorbar() # Show color bar of above image
plt.show()

Output >>>

matplotlib imshow - pi_chart with color

Show Image with cmap Parameter

Let’s play with plt.imshow() functions parameter. Here use cmap means color map to show a single-channel image in a different color.

single_channel = img[:,:,1] # get single channel data from img
plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(single_channel, cmap = "hot") # show image with hot color map
plt.colorbar()
plt.show()

Output >>>

If you want to show an image using a folder path, then follow the below code.

img2 = mpimg.imread("D:\\Private\\Wallpapers\\Pixels\\automobile-beautiful-car-1226458.jpg")
plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(img2)
plt.colorbar()
plt.show()

Output >>>

matplotlib-imshow-model

If, you don’t want to show color bar then remove 5’th no line.

Model image shows with hot color maps (cmap).

single_channel2_img = img2[:,:,1]
plt.figure(figsize=(16,9))
plt.axis("off")
plt.imshow(single_channel2_img, cmap="hot")
plt.colorbar()
plt.savefig("model_hot.png")
plt.show()
matplotlib imshow - model with hot cmap

Model image shows with nipy_spectral color maps (cmap).

matplotlib imshow - model with nipy_spectral

If we will generate an image with all cmaps then it takes more time. So for that follow the below code.

Below code get cmaps name as a string and split all cmap name as a single item of a list cmap_name_list

cmap = """Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r"""

cmap_name_list = cmap.split(sep = ", ")

Output >>>

['Accent',
 'Accent_r',
 'Blues',
 .
 .
 .
 'viridis_r',
 'winter',
 'winter_r']

Using cmap name create a unique address to store or save generated image in a folder.

save_image_addr_name = []
for i in range(len(cmap_name_list)):
    cmap_str = cmap_name_list[i]
    save_image_addr_name.append("D:\\\cmap_image\\\_"+"girl_" + cmap_name_list[i] + ".png")
    print(save_image_addr_name[i])

Output >>>

D:\\cmap_image\\_girl_Accent.png
D:\\cmap_image\\_girl_Accent_r.png
D:\\cmap_image\\_girl_Blues.png
D:\\cmap_image\\_girl_Blues_r.png
D:\\cmap_image\\_girl_BrBG.png
D:\\cmap_image\\_girl_BrBG_r.png
D:\\cmap_image\\_girl_BuGn.png
D:\\cmap_image\\_girl_BuGn_r.png
D:\\cmap_image\\_girl_BuPu.png
.
.
.
.
.
D:\\cmap_image\\_girl_twilight.png
D:\\cmap_image\\_girl_twilight_r.png
D:\\cmap_image\\_girl_twilight_shifted.png
D:\\cmap_image\\_girl_twilight_shifted_r.png
D:\\cmap_image\\_girl_viridis.png
D:\\cmap_image\\_girl_viridis_r.png
D:\\cmap_image\\_girl_winter.png
D:\\cmap_image\\_girl_winter_r.png

Using cmap_name_list and save_image_addr_name generate cmap image and save it define location with unique address.

for i in range(len(cmap_name_list)): 
    cmap_name = cmap_name_list[i]
    plt.figure(figsize=(16,9))
    plt.axis("off")
    
    print(cmap_name)

    plt.imshow(single_channel2_img, cmap=cmap_name)
    #plt.colorbar()
    #save_image_name1 = "D:\\cmap_image\\"+"girl" + cmap_list[i]
    print(save_image_addr_name[i])
    plt.savefig(save_image_addr_name[i], orientation='portrate', facecolor= "k")
    plt.show()

Output >>>

matplotlib imshow - model with all cmap values

Conclusion

In the matplotlib imshow blog, we learn how to read, show image and colorbar with a real-time example using the mpimg.imread, plt.imshow() and plt.colorbar() function. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file of matplotlib imshow source code

Visit the official site of matplotlib.org

The post Matplotlib imshow – Read & Show image using imread() & plt.imshow() appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-imshow/feed/ 0 873
Matplotlib savefig – Matplotlib Save Figure | Python matplotlib Tutorial https://indianaiproduction.com/matplotlib-savefig/ https://indianaiproduction.com/matplotlib-savefig/#respond Mon, 15 Jul 2019 14:00:16 +0000 https://indianaiproduction.com/?p=770 Matplotlib Save Figure After creating a plot or chart using the python matplotlib library and need to save and use it further. Then the matplotlib savefig function will help you. In this blog, we are explaining, how to save a figure using matplotlib? Import Library Matplotlib SaveFig (save figure) Different ways Syntax: plt.savefig(     …

Matplotlib savefig – Matplotlib Save Figure | Python matplotlib Tutorial Read More »

The post Matplotlib savefig – Matplotlib Save Figure | Python matplotlib Tutorial appeared first on Indian AI Production.

]]>
Matplotlib Save Figure

After creating a plot or chart using the python matplotlib library and need to save and use it further. Then the matplotlib savefig function will help you. In this blog, we are explaining, how to save a figure using matplotlib?

Import Library

import matplotlib.pyplot as plt # for data visualization 

Matplotlib SaveFig (save figure) Different ways

Syntax: plt.savefig(

                                   “File path with name or name”,
                                   dpi=None,
                                   quality = 99,
                                   facecolor=’w’,
                                   edgecolor=’w’,
                                   orientation=’portrait’,
                                   papertype=None,
                                   format=None,
                                   transparent=False,
                                   bbox_inches=None,
                                   pad_inches=0.1,
                                   frameon=None,
                                   metadata=None,

                                   )

Recommended Value Type for Parameters 

fname : str or file-like object
dpi : [ *None* | scalar > 0 | ‘figure’ ]quality : [ *None* | 1 <= scalar <= 100 ]
facecolor : color spec or None, optional
edgecolor : color spec or None, optional
orientation : {‘landscape’, ‘portrait’}
papertype : str
— ‘letter’, ‘legal’, ‘executive’, ‘ledger’, ‘a0’ through
‘a10’, ‘b0’ through ‘b10’
format : str —png, pdf, ps, eps and svg
transparent : bool
frameon : bool
bbox_inches : str or `~matplotlib.transforms.Bbox`, optional
pad_inches : scalar, optional
bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
metadata : dict, optional

Here, we are creating a simple pie chart and save it using plt.savefig() function. The file saves at program file location by default with “.png” format. You can change the file path. 

plt.pie([40,30,20]) # plot pie chart
plt.savefig("pie_char") # save above pie chart with name pie_chart
plt.show()

Output >>>

Pie Chart

Saved Image >>>

Matplotlib Savefig
pie_chart.png

Save Matplolib Figure using some parameters

plt.pie([40,30,20])
plt.savefig("pie_char2", # file name
            dpi = 100,  # dot per inch for resolution increase value for more resolution
            quality = 99, # "1 <= value <= 100" 100 for best qulity
            facecolor = "g" # image background color
           )
plt.show()

Output >>>

Pie Chart

Saved Image >>>

Matplotlib Savefig with parameters
pie_chart2.png

Example:

In bellow example, create plots and charts and show using subplot function. Then line no. “105(plt.savefig(“D:\\subplot_figure.png”)) save this subplot at user define location.

plt.figure(figsize=(23,27))

##----------------------------------------start 
#plt.subplot(3,2,1)
plt.subplot(321)
#********************************************Line Plot
days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
delhi_tem = [36.6, 37, 37.7,39,40.1,43,43.4,45,45.6,40.1,44,45,46.8,47,47.8]
mumbai_tem = [39,39.4,40,40.7,41,42.5,43.5,44,44.9,44,45,45.1,46,47,46]

plt.plot(days, delhi_tem, "mo--", linewidth = 3,
        markersize = 10, label = "Delhi tem")

plt.plot(days, mumbai_tem, "yo:", linewidth = 3,
        markersize = 10, label = "Mumbai tem}")

plt.title("Delhi  & Mumbai Temperature Line Plot", fontsize=15)
plt.xlabel("days",fontsize=13)
plt.ylabel("temperature",fontsize=13)
plt.legend(loc = 4)
plt.grid(color='w', linestyle='-', linewidth=2)

#---------------------------------------------------------------end

plt.subplot(3,2,2) ##-------------------------------------------------start
#****************************************************************histograms
ml_students_age = np.random.randint(18,45, (100))
py_students_age = np.random.randint(15,40, (100))
bins = [15,20,25,30,35,40,45]

plt.hist([ml_students_age, py_students_age], bins, rwidth=0.8, histtype = "bar",
         orientation='vertical', color = ["m", "y"], label = ["ML Student", "Py Student"])

plt.title("ML & Py Students age histograms")
plt.xlabel("Students age cotegory")
plt.ylabel("No. Students age")
plt.legend()
#----------------------------------------------------------------------end

plt.subplot(3,2,3) ##--------------------------------------------start
#************************************************************Bar Chart
classes = ["Python", "R", "AI", "ML", "DS"]
class1_students = [30, 10, 20, 25, 10] # out of 100 student in each class
class2_students = [40, 5, 20, 20, 10]
class3_students = [35, 5, 30, 15, 15]
classes_index = np.arange(len(classes))

width = 0.2

plt.barh(classes_index, class1_students, width , color = "b",
        label =" Class 1 Students") #visible=False

plt.barh(classes_index + width, class2_students, width , color = "g",
        label =" Class 2 Students") 

plt.barh(classes_index + width + width, class3_students, width , color = "y",
        label =" Class 3 Students") 

plt.yticks(classes_index + width, classes, rotation = 20)
plt.title("Bar Chart of IAIP Class Bar Chart", fontsize = 18)
plt.ylabel("Classes",fontsize = 15)
plt.xlabel("No. of Students", fontsize = 15)
plt.legend()
#--------------------------------------------------------------------end

plt.subplot(3,2,4) ##------------------------------------------------start
#**************************************************************Scatter Plot
df_google_play_store_apps = pd.read_csv("D:\\Private\Indina AI Production\Kaggel Dataset\google-play-store-apps\googleplaystore.csv", nrows = 1000)
x = df_google_play_store_apps["Rating"]
y = df_google_play_store_apps["Reviews"]
plt.scatter(x,y, c = "r", marker = "*", s = 100, alpha=0.5, linewidths=10,
           edgecolors="g" )#verts="<"

plt.scatter(x,df_google_play_store_apps["Installs"], c = "y", marker = "o", s = 100, alpha=0.5, linewidths=10,
           edgecolors="c" )
plt.title("Google Play Store Apps Scatter plot")
plt.xlabel("Rating")
plt.ylabel("Reviews & Installs")
#----------------------------------------------------------------------end


plt.subplot(3,2,5) ##-----------------------------------------start
#*************************************************************Pie plot
classes = ["Python", 'R', 'Machine Learning', 'Artificial Intelligence', 
           'Data Sciece']
class1_students = [45, 15, 35, 25, 30]
explode = [0.03,0,0.1,0,0]
colors = ["c", 'b','r','y','g']
textprops = {"fontsize":15}

plt.pie(class1_students, 
        labels = classes, 
        explode = explode, 
        colors =colors, 
        autopct = "%0.2f%%", 
        shadow = True, 
        radius = 1.4,
       startangle = 270, 
        textprops =textprops)
#------------------------------------------------------end


plt.subplot(3,2,6, projection='polar', facecolor='k' ,frameon=True)

plt.savefig("D:\\subplot_figure.png") # save subplots at drive "D" of name subplot_figure
plt.show()

Output >>>

Matplotlib Subplots

Saved Image >>>

Matplotlib Savefig - subplots
subplot_figure.png

CONCLUSION

In the matplotlib save figure blog, we learn how to save figure with a real-time example using the plt.savefig() function. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file of matplotlib savefig source code

Visit the official site of matplotlib.org

The post Matplotlib savefig – Matplotlib Save Figure | Python matplotlib Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-savefig/feed/ 0 770
Matplotlib Subplot – plt.subplot() | Python Matplolib Tutorial https://indianaiproduction.com/matplotlib-subplot/ https://indianaiproduction.com/matplotlib-subplot/#respond Sun, 14 Jul 2019 14:34:05 +0000 https://indianaiproduction.com/?p=765 Matplotlib Subplot This blog under construction but you can download sourse code In matplolib subplot blog, discusing on how to plot subplots using plt.subplot() function. Imort Libraries Create matplotlib subplotls Creating 4 subplot with 2 rows and 2 columns. Output >>> Download Jupyter file of matplotlib Subplot source code

The post Matplotlib Subplot – plt.subplot() | Python Matplolib Tutorial appeared first on Indian AI Production.

]]>
Matplotlib Subplot

This blog under construction but you can download sourse code

In matplolib subplot blog, discusing on how to plot subplots using plt.subplot() function.

Imort Libraries

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
from matplotlib import style

Create matplotlib subplotls

Creating 4 subplot with 2 rows and 2 columns.

# Create 4 subplot (2- rows and 2 - columns)
plt.subplot(2,2,1)

plt.subplot(2,2,2)

plt.subplot(2,2,3)

plt.subplot(2,2,4)

plt.show()

Output >>>

Download Jupyter file of matplotlib Subplot source code

The post Matplotlib Subplot – plt.subplot() | Python Matplolib Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-subplot/feed/ 0 765
Matplotlib Scatter Plot – plt.scatter() | Python Matplotlib Tutorial https://indianaiproduction.com/matplotlib-scatter-plot/ https://indianaiproduction.com/matplotlib-scatter-plot/#comments Sun, 14 Jul 2019 06:57:42 +0000 https://indianaiproduction.com/?p=729 Matplotlib Scatter Plot In the matplotlib scatter plot blog will discuss, how to draw a scatter plot using python matplotlib plt.scatter() function. The plt.scatter() function help to plot two-variable datasets in point or a user-defined format. Here, we will be plotting google play store apps scatter plot. Import Libraries Import Dataset The data frame contains …

Matplotlib Scatter Plot – plt.scatter() | Python Matplotlib Tutorial Read More »

The post Matplotlib Scatter Plot – plt.scatter() | Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
Matplotlib Scatter Plot

In the matplotlib scatter plot blog will discuss, how to draw a scatter plot using python matplotlib plt.scatter() function. The plt.scatter() function help to plot two-variable datasets in point or a user-defined format. Here, we will be plotting google play store apps scatter plot.

Import Libraries

import matplotlib.pyplot as plt # For visualization
import pandas as pd # for data cleaing & analysis

Import Dataset

# Dataset taken from kaggel.com
df_google_play_store_apps = pd.read_csv("D:\\Private\Indina AI Production\Kaggel Dataset\google-play-store-apps\googleplaystore.csv")
df_google_play_store_apps.shape # Get shape of dataset in rows and colms
Output >>>
          (10841, 13) # (rows, colomns) of data frame

The data frame contains 10841 rows and we wants only 1000 rows , so for use nrow parameter of pd.DataFrame(). You can work on hole dtaset its your choice.

df_google_play_store_apps = pd.read_csv("D:\\Private\Indina AI Production\Kaggel Dataset\google-play-store-apps\googleplaystore.csv", 
                                        nrows = 1000)
df_google_play_store_apps.shape ## Get shape of dataset in rows and colms
Output >>>
          (1000, 13) # (rows, colomns) of data frame

View Data Frame Sample 

df_google_play_store_apps

Output >>>

Google Play Store Apps Data Frame

The data frame contain numeric and string typle value and for scatter plot need numeric value. So, we are ploting scatter plot of Google Play Store Apps Data Frame 1as x and Reviews as y coloms data.

x = df_google_play_store_apps["Rating"]
y = df_google_play_store_apps["Reviews"]

Plot Scatter plot using matplotlib

Syntax : plt.scatter(

                                      x,
                                      y,
                                      s=None,
                                      c=None,
                                      marker=None, 
                                      cmap=None,
                                      norm=None,
                                      vmin=None,
                                      vmax=None,
                                      alpha=None,
                                      linewidths=None,
                                      verts=None, ### same work like – marker
                                      edgecolors=None,
                                      *,
                                      data=None,
                                      **kwargs,
                                      )

plt.scatter(x,y) # Draw scatter plot with parameter x and y
plt.show()

Output >>>

Matplotlib Scatter Plot
Fig 1.1 – Matplotlib Scatter Plot

Show scatter plot with title, xlabel and ylabel.

plt.scatter(x,y)
plt.title("Google Play Store Apps Scatter plot")
plt.xlabel("Rating")
plt.ylabel("Reviews")
plt.show()

Output >>>

Matplotlib Scatter Plot
Fig 1.1 – Matplotlib Scatter Plot with functions

Ploting Scatter plot with parameters 

plt.figure(figsize = (16,9)) # figure size ratio 16:9
plt.scatter(x,y, c = "r", marker = "*", s = 100, alpha=0.5, linewidths=10,
           edgecolors="g" )#verts="<"
plt.title("Google Play Store Apps Scatter plot")
plt.xlabel("Rating")
plt.ylabel("Reviews")
plt.show()

Output >>>

Matplotlib Scatter Plot with parameters
Fig 1.3 – Matplotlib Scatter Plot

Plot Two Scatter Plot in one plot

plt.figure(figsize = (16,9))
plt.scatter(x,y, c = "r", marker = "*", s = 100, alpha=0.5, linewidths=10,
           edgecolors="g" )#verts="<"

plt.scatter(x,df_google_play_store_apps["Installs"], c = "y", marker = "o", s = 100, alpha=0.5, linewidths=10,
           edgecolors="c" )
plt.title("Google Play Store Apps Scatter plot")
plt.xlabel("Rating")
plt.ylabel("Reviews & Installs")
plt.show()

Output >>>

Matplotlib two scatter plot
Fig 1.4 – Matplotlib two scatter plot

Conclusion

In the matplotlib plt.scatter() plot blog, we learn how to plot one and multiple scatter plot with a real-time example using the plt.scatter() method. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file of matplotlib scatter plot source code

Visit the official site of matplotlib.org

The post Matplotlib Scatter Plot – plt.scatter() | Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-scatter-plot/feed/ 1 729
Matplotlib Pie Chart – plt.pie() | Python Matplotlib Tutorial https://indianaiproduction.com/matplotlib-pie-chart/ https://indianaiproduction.com/matplotlib-pie-chart/#comments Fri, 12 Jul 2019 11:17:36 +0000 https://indianaiproduction.com/?p=712 Matplotlib Pie Chart In this blog, we will work on how to draw a matplotlib pie chart? To draw pie char use plt.pie() function. The matplotkib plt.pie() function help to plot pie chart of given numeric data with labels. It also support different parameters which help to show better. Importing Library Plotting Matplotlib Pie Chart …

Matplotlib Pie Chart – plt.pie() | Python Matplotlib Tutorial Read More »

The post Matplotlib Pie Chart – plt.pie() | Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
Matplotlib Pie Chart

In this blog, we will work on how to draw a matplotlib pie chart? To draw pie char use plt.pie() function. The matplotkib plt.pie() function help to plot pie chart of given numeric data with labels. It also support different parameters which help to show better.

Importing Library

import matplotlib.pyplot as plt

Plotting Matplotlib Pie Chart

plt.pie([1]) # Plot pie chart of value [1]
plt.show() # To show Pie chart

Output >>>

Matplotlib Simple pie Chart
Fig 1.1 – Matplotlib Simple pie Chart

Importing Dataset

classes = ["Python", 'R', 'Machine Learning', 'Artificial Intelligence', 
           'Data Sciece']
class1_students = [45, 15, 35, 25, 30]

Plotting pie chart using real dataset.

plt.pie(class1_students, labels = classes)
plt.show()

Output >>>

Matplotlib pie chart using dataset
Fig 1.2 – Matplotlib pie chart using dataset

Below are the different parameters of plt.pie() functions.

Syntax: plt.pie(
[‘x’,
‘explode=None’,
‘labels=None’,
‘colors=None’,
‘autopct=None’,
‘pctdistance=0.6’,
‘shadow=False’,
‘labeldistance=1.1’,
‘startangle=None’,
‘radius=None’,
‘counterclock=True’,
‘wedgeprops=None’,
‘textprops=None’,
‘center=(0, 0)’,
‘frame=False’,
‘rotatelabels=False’,
‘*’,
‘data=None’],

)

x : array-like
explode : array-like, optional, default: None
labels : list, optional, default: None
colors : array-like, optional, default: None
autopct : None (default), string, or function, optional
pctdistance : float, optional, default: 0.6
shadow : bool, optional, default: False
labeldistance : float, optional, default: 1.1
startangle : float, optional, default: None
radius : float, optional, default: None
counterclock : bool, optional, default: True
wedgeprops : dict, optional, default: None
—- example, you can pass in wedgeprops = {‘linewidth’: 3}
textprops : dict, optional, default: None
center : list of float, optional, default: (0, 0)
frame : bool, optional, default: False
rotatelabels : bool, optional, default: False

Plotting pie chart using different parameters.

explode = [0.03,0,0.1,0,0] # To slice the perticuler section
colors = ["c", 'b','r','y','g'] # Color of each section
textprops = {"fontsize":15} # Font size of text in pie chart

plt.pie(class1_students, # Values
        labels = classes, # Labels for each sections
        explode = explode, # To slice the perticuler section
        colors =colors, # Color of each section
        autopct = "%0.2f%%", # Show data in persentage for with 2 decimal point
        shadow = True, # Showing shadow of pie chart
        radius = 1.4, # Radius to increase or decrease the size of pie chart 
       startangle = 270, # Start angle of first section
        textprops =textprops) 

plt.show() # To show pie chart only

Output >>>

Matplotlib pie chart using parameters
Fig 1.3 – Matplotlib pie chart using parameters

Plotting pie chart using a legend – plt.legend()

explode = [0.03,0,0.1,0,0] # To slice the perticuler section
colors = ["c", 'b','r','y','g'] # Color of each section
textprops = {"fontsize":15} # Font size of text in pie chart

plt.pie(class1_students, # Values
        labels = classes, # Labels for each sections
        explode = explode, # To slice the perticuler section
        colors =colors, # Color of each section
        autopct = "%0.2f%%", # Show data in persentage for with 2 decimal point
        shadow = True, # Showing shadow of pie chart
        radius = 1.4, # Radius to increase or decrease the size of pie chart 
       startangle = 270, # Start angle of first section
        textprops =textprops) 
plt.legend() # To show legend
plt.show() # To show pie chart only

Output >>>

Matplotlib pie chart using legend
Fig 1.4 -Matplotlib pie chart using legend

Plotting pie chart using more parameters than above and width = 1.

plt.figure(figsize = (3,2))
wedgeprops = {"linewidth": 4, 'width':1, "edgecolor":"k"} # Width = 1
plt.pie(
        class1_students, 
        labels = classes, 
        explode = explode, 
        colors = colors, 
        autopct = "%0.2f%%", 
        pctdistance = 0.6, 
        shadow =True, 
        labeldistance = 1.6, 
        startangle = 270,
        radius = 1, 
        counterclock = True, 
        wedgeprops = wedgeprops,
        textprops = textprops,
        center=(2, 3),
        frame=True,
        rotatelabels=True
        ) 
plt.show()

Output >>>

Matplotlib pie chart using more parameters
Fig 1.5 – Matplotlib pie chart using more parameters

Change the Value of width by 2,3,4 then you will gote below the pie charts.

Fig 1.6 – Matplotlib pie chart with a width value 2
Fig 1.7 – Matplotlib pie chart with width value 3

Plotting another pie charts for fun.

import numpy as np
plt.figure(figsize=(7,4))
#plt.figure(figsize=(16,9)

colors = ['r','w','r','w','r','w','r','w','r','w','r','w','r','w','r','w','r','w','r','w']
labels = np.ones(20)
#labels = [1.0,1.0,1.0,1.0,1.0,.........,1.0]

plt.pie([1], colors="k", radius = 2.05)
plt.pie(labels, colors=colors, radius = 2.0)

plt.pie([1], colors="g", radius = 1.8)
plt.pie([1], colors="y", radius = 1.6)
plt.pie([1], colors="c", radius = 1.3)
plt.pie([1], colors="b", radius = 1.1)
plt.pie([1], colors="m", radius = 0.9)

plt.pie([1], colors="b", radius = 0.31)
plt.pie(labels, colors=colors, radius = 0.3)

plt.pie([1], colors="w", radius = 0.2)
plt.pie([1], colors="k", radius = 0.1)

plt.show()

Output >>>

Fig 1.8 – Matplotlib pie charts

Conclusion

In the matplotlib plt.pie chart blog, we learn how to plot one and multiple pie charts with a real-time example using the plt.pie() method. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file of matplotlib bar chart source code

Visit the official site of matplotlib.org

The post Matplotlib Pie Chart – plt.pie() | Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-pie-chart/feed/ 1 712
Matplotlib Bar Chart – Python Matplotlib Tutorial https://indianaiproduction.com/matplotlib-bar-chart/ https://indianaiproduction.com/matplotlib-bar-chart/#comments Mon, 08 Jul 2019 18:10:26 +0000 https://indianaiproduction.com/?p=664 Matplotlib Bar Chart To visualize value associated with categorical data in the bar format use matplotlib bar chart plt.bar() or plt.barh() methods. Importing Libary to Plot Bar Chart Importing Data set to plot Bar Chart This dataset of “Indian Artificial Intelligence Production Class” (IAIP).  Instead of it use your business dataset. Plot Bar Chart with a …

Matplotlib Bar Chart – Python Matplotlib Tutorial Read More »

The post Matplotlib Bar Chart – Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
Matplotlib Bar Chart

To visualize value associated with categorical data in the bar format use matplotlib bar chart plt.bar() or plt.barh() methods.

Importing Libary to Plot Bar Chart

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style

Importing Data set to plot Bar Chart

This dataset of “Indian Artificial Intelligence Production Class” (IAIP).  Instead of it use your business dataset.

# Dataset of 'Indian Artificial Intelligence Production (IAIP) Class"

#classes = ["Python", "R", "Artificial Intelligence", "Machine Learning", "Data Science"]

classes = ["Python", "R", "AI", "ML", "DS"]
class1_students = [30, 10, 20, 25, 10] # out of 100 student in each class
class2_students = [40, 5, 20, 20, 10]
class3_students = [35, 5, 30, 15, 15]

Plot Bar Chart with a different way

To plot bar chart using the matplotlib python library, use plt.bar() or plt.barh() methods.

Syntax: plt.bar(
                             x,
                             height,
                             width=0.8,
                             bottom=None,
                             *,
                             align=’center’,
                             data=None,
                             **kwargs,
                             )

Parameters

———-
x : sequence of scalars
height : scalar or sequence of scalars
width : scalar or array-like, optional …….(default: 0.8).
bottom : scalar or array-like, optional
align : {‘center’, ‘edge’}, optional, ……….default: ‘center’


Other Parameters
—————-

color : scalar or array-like, optional
edgecolor : scalar or array-like, optional
linewidth : scalar or array-like, optional
tick_label : string or array-like, optional ……. name of Bar
xerr, yerr : scalar or array-like of shape(N,) or shape(2,N), optional
ecolor : scalar or array-like, optional, default: ‘black’
capsize : scalar, optional
error_kw : dict, optional
log : bool, optional, default: False
orientation : {‘vertical’, ‘horizontal’}, optional


See also
——–
barh: Plot a horizontal bar plot.

Other optional kwargs:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
===== alpha: float or None
animated: bool
antialiased: unknown
capstyle: {‘butt’, ’round’, ‘projecting’}
clip_box: `.Bbox`
clip_on: bool
clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
===== color: color
contains: callable
===== edgecolor: color or None or ‘auto’
===== facecolor: color or None
===== figure: `.Figure`
fill: bool
gid: str
hatch: {‘/’, ‘\\’, ‘|’, ‘-‘, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’}
in_layout: bool
joinstyle: {‘miter’, ’round’, ‘bevel’}
===== label: object
===== linestyle: {‘-‘, ‘–‘, ‘-.’, ‘:’, ”, (offset, on-off-seq), …}
===== linewidth: float or None for default
path_effects: `.AbstractPathEffect`
picker: None or bool or float or callable
rasterized: bool or None
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
transform: `.Transform`
url: str
===== visible: bool
zorder: float

plt.bar(classes, class1_students) # Plot vertical Bar Chart

Output >>>

Matplotlib Bar Chart - 1
Fig 1.1 – Matplotlib Vertical Bar Chart
plt.barh(classes, class1_students) # Plot horizontal bar chart 

Output >>>

Matplotlib Horizontal Bar Chart - 2
Fig 1.2 – Matplotlib Horizontal Bar Chart

Use multiple parameters of plt.bar() method

plt.bar(classes, class1_students, width = 0.2, align = "edge", color = "y",
       edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
       label =" Class 1 Students", visible=False)
#visible = True ## bar Chart will hide 

Output >>> 

Matplotlib Bar Chart with multiple parameters - 3
Fig 1.3 – Matplotlib Vertical Bar Chart with multiple parameters

Increase figure size and use style.

style.use("ggplot") 
plt.figure(figsize=(16,9)) # figure size with ratio 16:9
plt.bar(classes, class1_students, width = 0.6, align = "edge", color = "k",
       edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
       label =" Class 1 Students") #visible=False

Output >>>

Matplotlib Vertical Bar Chart with multiple parameters - 4
Fig 1.4 – Matplotlib Vertical Bar Chart with multiple parameters

Plot horizontal bar chart with the above specification. 

plt.figure(figsize=(16,9))
plt.barh(classes, class1_students,  align = "edge", color = "k",
       edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
       label =" Class 1 Students") #visible=False

Output >>>

Matplotlib Horizontal Bar Chart with multiple parameters - 5
Fig 1.5 – Matplotlib Horizontal Bar Chart with multiple parameters

Decorating bar chart using multiple functions.

plt.figure(figsize=(16,9))
plt.bar(classes, class1_students, width = 0.6, align = "edge", color = "k",
       edgecolor = "m", linewidth = 5, alpha = 0.9, linestyle = "--",
       label =" Class 1 Students") #visible=False

plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.xlabel("Classes",fontsize = 15)
plt.ylabel("No. of Students", fontsize = 15)
plt.show()

Output >>>

Matplotlib Horizontal Bar Chart with multiple functions- 6
Fig 1.6 – Matplotlib Horizontal Bar Chart with multiple functions

Trying to plot two bar charts with a different dataset.

plt.figure(figsize=(16,9))

plt.bar(classes, class1_students, width = 0.2, color = "b",
        label =" Class 1 Students") #visible=False

plt.bar(classes, class2_students, width = 0.2, color = "g",
        label =" Class 2 Students") 

plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.xlabel("Classes",fontsize = 15)
plt.ylabel("No. of Students", fontsize = 15)
plt.show()

Output >>>

Matplotlib two Bar Chart - 7
Fig 1.7 – Matplotlib two Bar Chart

The above code not generating two bar charts in one figure but they are overlapping. So use the below code to plot multiple bar charts. In below chart plot three bar charts using three different datasets.

plt.figure(figsize=(16,9))

classes_index = np.arange(len(classes))

width = 0.2

plt.bar(classes_index, class1_students, width , color = "b",
        label =" Class 1 Students") #visible=False

plt.bar(classes_index + width, class2_students, width , color = "g",
        label =" Class 2 Students") 

plt.bar(classes_index + width + width, class3_students, width , color = "y",
        label =" Class 2 Students") 

plt.xticks(classes_index + width, classes, rotation = 20)
plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.xlabel("Classes",fontsize = 15)
plt.ylabel("No. of Students", fontsize = 15)
plt.show()

Output >>>

Matplotlib Three Bar Chart - 7
Fig 1.8 – Matplotlib Three Bar Chart

Plot Matplotlib Horizontal bar chart with the above specification.

plt.figure(figsize=(16,9))

classes_index = np.arange(len(classes))

width = 0.2

plt.barh(classes_index, class1_students, width , color = "b",
        label =" Class 1 Students") #visible=False

plt.barh(classes_index + width, class2_students, width , color = "g",
        label =" Class 2 Students") 

plt.barh(classes_index + width + width, class3_students, width , color = "y",
        label =" Class 3 Students") 

plt.yticks(classes_index + width, classes, rotation = 20)
plt.title("Bar Chart of IAIP Class", fontsize = 18)
plt.ylabel("Classes",fontsize = 15)
plt.xlabel("No. of Students", fontsize = 15)
plt.legend()
plt.show()

Output >>>

Matplotlib Three Horizontal Bar Chart - 9
Fig 1.9 – Matplotlib Three Horizontal Bar Chart

Conclusion

In the matplotlib bar chart blog, we learn how to plot one and multiple bar charts with a real-time example using plt.bar() and plt.barh() methods. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file of matplotlib bar chart source code

Visit to the official site of matplotlib.org

The post Matplotlib Bar Chart – Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-bar-chart/feed/ 1 664
Matplotlib Histogram – Python Matplotlib Tutorial https://indianaiproduction.com/matplotlib-histogram/ https://indianaiproduction.com/matplotlib-histogram/#respond Fri, 28 Jun 2019 14:03:06 +0000 https://indianaiproduction.com/?p=551 Python Matplotlib Histogram Matplotlib histogram is a representation of numeric data in the form of a rectangle bar. Each bar shows some data,  which belong to different categories. To plot histogram using python matplotlib library need plt.hist() method. Syntax: plt.hist(x,bins=None,range=None,density=None,weights=None,cumulative=False,bottom=None,histtype=’bar’,align=’mid’,orientation=’vertical’,rwidth=None,log=False,color=None,label=None,stacked=False,normed=None,*,data=None,**kwargs,) The plt.hist() method has lots of parameter, So we are going to cover some of …

Matplotlib Histogram – Python Matplotlib Tutorial Read More »

The post Matplotlib Histogram – Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
Python Matplotlib Histogram

Matplotlib histogram is a representation of numeric data in the form of a rectangle bar. Each bar shows some data,  which belong to different categories. To plot histogram using python matplotlib library need plt.hist() method.

Syntax: plt.hist(
x,
bins=None,
range=None,
density=None,
weights=None,
cumulative=False,
bottom=None,
histtype=’bar’,
align=’mid’,
orientation=’vertical’,
rwidth=None,
log=False,
color=None,
label=None,
stacked=False,
normed=None,
*,
data=None,
**kwargs,
)

The plt.hist() method has lots of parameter, So we are going to cover some of these. Which is most important but you have to try each and every one to best practice.

Importing Packages

import matplotlib.pyplot as plt
import numpy as np
import random

Generate Data

ml_students_age = np.random.randint(18,45, (100))
py_students_age = np.random.randint(15,40, (100))

Printing Generated Data

print(ml_students_age)
print(py_students_age)
[22 20 22 42 40 21 35 23 22 24 24 21 44 25 24 40 41 44 44 44 19 23 33 27
 29 21 28 18 34 31 32 29 32 18 39 23 26 24 33 21 20 26 38 25 38 31 30 20
 39 32 41 20 24 27 26 22 33 31 22 38 37 33 34 28 28 34 34 34 33 40 34 23
 33 39 39 25 42 27 23 28 33 31 44 39 28 26 25 29 23 39 39 38 41 34 26 38
 35 42 31 29]
[21 29 26 22 21 20 29 29 26 38 28 32 35 20 21 16 39 26 39 31 27 23 29 37
 32 30 21 36 18 32 17 20 18 28 17 30 29 26 35 31 19 19 19 39 21 26 27 17
 23 22 37 21 35 37 16 33 36 39 31 33 37 26 26 17 17 17 23 27 28 32 38 20
 19 33 24 36 34 27 25 21 33 15 39 15 37 27 32 35 21 37 16 38 36 18 39 21
 29 27 18 30]

Plotting Histogram Using Matplotlib

Plotting histogram of machine learning students age.

plt.hist(ml_students_age)

plt.title("ML Students age histograms")
plt.xlabel("Students age cotegory")
plt.ylabel("No. Students age")
plt.show()

Output >>>

Matplotlib Histogram of ML students age
Fig 1.1 – Matplotlib Histogram of ML students age

Plotting Histogram Using Matplotlib with parameters

bins = [15,20,25,30,35,40,45] # category of ML students age on x axis
plt.figure(figsize = (16,9)) # size of histogram in 16:9 format


plt.hist(ml_students_age, bins, rwidth=0.8, histtype = "bar",
         orientation='vertical', color = "m", label = "ML Student")

plt.title("ML Students age histograms")
plt.xlabel("Students age cotegory")
plt.ylabel("No. Students age")
plt.legend()
plt.show()

Output >>>

Matplotlib Histogram of ML students age with parameters
Fig 1.2 – Matplotlib Histogram of ML students age with parameters

Plotting two Histogram Using Matplotlib with parameters

from matplotlib import style # for style 
style.use("ggplot") # return grid
plt.figure(figsize = (16,9)) 

plt.hist([ml_students_age, py_students_age], bins, rwidth=0.8, histtype = "bar",
         orientation='vertical', color = ["m", "y"], label = ["ML Student", "Py Student"])

#plt.hist(py_students_age, bins, rwidth=0.8, histtype = "bar",
#         orientation='vertical', color = "y", label = "Py Student")

plt.title("ML & Py Students age histograms")
plt.xlabel("Students age cotegory")
plt.ylabel("No. Students age")
plt.legend()
plt.show()

Output >>>

Matplotlib Histogram of ML & Py students age with parameters
Fig 1.3 – Matplotlib Histogram of ML & Py students age with parameters

Conclusion

In matplotlib histogram blog, we learn how to plot one and multiple histograms with a real-time example using plt.hist() method. Along with that used different method with different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file matplotlib line plot source code

Visite to the official site of matplotlib.org

The post Matplotlib Histogram – Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-histogram/feed/ 0 551
Matplotlib Line Plot – Python Matplotlib Tutorial https://indianaiproduction.com/matplotlib-line-plot/ https://indianaiproduction.com/matplotlib-line-plot/#respond Sun, 23 Jun 2019 13:22:45 +0000 https://indianaiproduction.com/?p=450 Matplotlib Line Plot In this blog, you will learn how to draw a matplotlib line plot with different style and format. The pyplot.plot() or plt.plot() is a method of matplotlib pyplot module use to plot the line. Syntax: plt.plot(*args, scalex=True, scaley=True, data=None, **kwargs) Import pyplot module from matplotlib python library using import keyword and give …

Matplotlib Line Plot – Python Matplotlib Tutorial Read More »

The post Matplotlib Line Plot – Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
Matplotlib Line Plot

In this blog, you will learn how to draw a matplotlib line plot with different style and format.

The pyplot.plot() or plt.plot() is a method of matplotlib pyplot module use to plot the line.

Syntax: plt.plot(*args, scalex=True, scaley=True, data=None, **kwargs)

Import pyplot module from matplotlib python library using import keyword and give short name plt using as  keyword.

import matplotlib.pyplot as plt 

Import Dataset of 15 days Delhi temperature record. The dataset in the form of list data type, you can use NumPy array, tuple, etc.

days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
temperature = [36.6, 37, 37.7,39,40.1,43,43.4,45,45.6,40.1,44,45,46.8,47,47.8]

Plot the line using plt.plot() method and show it using plt.show() method. Here, give a parameter x as a days and y as a temperature to plt.plot() 

plt.plot(days, temperature)
plt.show()

Output >>>

Matplotlib line plot - 15 days Delhi Temperature graph
Fig 1.1 – 15 days temperature record of Delhi city

Fig 1.1 not showing any useful information, because it has no x-axis,  y-axis, and title. So for this, you can use the below methods.

Syntax: plt.xlabel(xlabel, fontdict=None, labelpad=None, **kwargs)

Syntax: plt.ylabel(ylabel, fontdict=None, labelpad=None, **kwargs)

Syntax: plt.title(label, fontdict=None, loc=‘center’, pad=None, **kwargs)

# plot line with x-axis, y-axis and title
plt.plot(days, temperature)
plt.title("Delhi Temperature")
plt.xlabel("days")
plt.ylabel("temperature")
plt.show()

Output >>>

Matplotlib line plot - 15 days Delhi Temperature graph with information
Fig 1.2 – 15 days temperature record of Delhi city with information

Observe Fig 1.1 and Fig 1.2, the starting axis value take automatically by plt.plot() method. If you want to set it manually, then use plt.axis() method.

Syntax: plt.axis(xmin, xmax, ymin, ymax)

plt.plot(days, temperature)
plt.axis([0,30, 0,50]) # set axis 
plt.title("Delhi Temperature")
plt.xlabel("days")
plt.ylabel("temperature")
plt.show()

Output >>>

Matplotlib line plot - 15 days Delhi Temperature graph set with axis
Fig 1.3 – 15 days temperature record of Delhi city set with the axis

The plt.plot() method has much more parameter. So, let’s play with some of them.

plt.plot(days, temperature, color = "g", marker = "o", linestyle= "--", linewidth = 3,
        markersize = 10)
plt.title("Delhi Temperature")
plt.xlabel("days")
plt.ylabel("temperature")
plt.show()

Output >>>

Matplotlib line plot - 15 days Delhi Temperature graph set with axis
Fig 1.4 – 15 days temperature record of Delhi city with parameters

Color Parameter Values

Character Color
b blue
g green
r red
c cyan
m magenta
y yellow
k black
w white

Marker Parameter Values

Character Description
. point marker
, pixel marker
o circle marker
v triangle_down marker
^ triangle_up marker
< triangle_left marker
> triangle_right marker
1 tri_down marker
2 tri_up marker
3 tri_left marker
4 tri_right marker
s square marker
p pentagon marker
* star marker
h hexagon1 marker
H hexagon2 marker
+ plus marker
x x marker
D diamond marker
d thin_diamond marker
| vline marker
_ hline marker

Line Style parameters values

Character Description
_ solid line style
dashed line style
_. dash-dot line style
: dotted line style

So, try to use different values of the above parameters. Then you will get a different output.

If you want to change the bar chart’s background color and add grid then use style.use() method. For this first, need to import the style module from matplotlib. 

Syntax: style.use(style)

To add a legend in the graph to describe more information about it, use plt.legend().

Syntax: plt.legend(*args, **kwargs)

from matplotlib import style # import style module
style.use("ggplot") # give ggplot parameter value to use() method
plt.plot(days, temperature, "mo--", linewidth = 3,
        markersize = 10, label = "Temp line")
plt.title("Delhi Temperature", fontsize=15)
plt.xlabel("days",fontsize=13)
plt.ylabel("temperature",fontsize=13)
plt.legend(loc = 4) 
plt.show()

Output >>>

Matplotlib line plot - 15 days Delhi Temperature graph with style and legend
Fig 1.5 – 15 days temperature record of Delhi city with style and legend

Matplotlib Multiple Lines Plot

To plot multiple lines using a matplotlib line plot method use more plt.plot() method similar to your dataset.

Here, we have 15 days temperature record of Delhi and Mumbai city

days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
delhi_tem = [36.6, 37, 37.7,39,40.1,43,43.4,45,45.6,40.1,44,45,46.8,47,47.8]
mumbai_tem = [39,39.4,40,40.7,41,42.5,43.5,44,44.9,44,45,45.1,46,47,46]

plt.plot(days, delhi_tem, "mo--", linewidth = 3,
        markersize = 10, label = "Delhi tem")

plt.plot(days, mumbai_tem, "yo:", linewidth = 3,
        markersize = 10, label = "Mumbai tem}")

plt.title("Delhi  & Mumbai Temperature", fontsize=15)
plt.xlabel("days",fontsize=13)
plt.ylabel("temperature",fontsize=13)
plt.legend(loc = 4)
plt.show()

Output >>>

Matplotlib line plot - 15 days Delhi & Mumbai city Temperature graph
Fig 1.6 – 15 days temperature record of Delhi & Mumbai city

If you want to change or add grid then use plt.grid() method.

Syntax: plt.grid(b=None, which=‘major’, axis=‘both’, **kwargs)

plt.plot(days, delhi_tem, "mo-", linewidth = 3,
        markersize = 10, label = "Delhi tem")

plt.plot(days, mumbai_tem, "k-", linewidth = 5,
        markersize = 10, label = "Mumbai tem")

plt.title("Delhi  & Mumbai Temperature", fontsize=15)
plt.xlabel("days",fontsize=13)
plt.ylabel("temperature",fontsize=13)
plt.legend(loc = 4)
plt.grid(color='c', linestyle='-', linewidth=2) # grid with parameter
plt.show()

Output >>>

Matplotlib line plot - 15 days Delhi & Mumbai city Temperature graph with grid
Fig 1.7 – 15 days temperature record of Delhi & Mumbai city with a grid

In this way, you can plot multiple lines using matplotlib line plot method. 

Note: When you use style.use(“ggplot”). after that, no need to it again because it uses once and applies for all graph.

Conclusion

In matplotlib line plot blog, we learn how to plot one and multiple lines with a real-time example using plt.plot() method. Along with that used different method with different parameter. Suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file matplotlib line plot source code

Visite to the official site of matplotlib.org

The post Matplotlib Line Plot – Python Matplotlib Tutorial appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/matplotlib-line-plot/feed/ 0 450
Python Matplotlib Tutorial – Mastery in Matplotlib Library https://indianaiproduction.com/python-matplotlib-tutorial/ https://indianaiproduction.com/python-matplotlib-tutorial/#respond Sat, 22 Jun 2019 10:09:40 +0000 https://indianaiproduction.com/?p=438 Python Matplotlib Tutorial After complication of python NumPy Tutorial and python pandas tutorial. Now, we jump on the python matplotlib tutorial to become a master in it. What is python matplotlib? Matplotlib is a 2D and 3D graph plotting python library. It also supports to create animations and images. This is an advanced part of …

Python Matplotlib Tutorial – Mastery in Matplotlib Library Read More »

The post Python Matplotlib Tutorial – Mastery in Matplotlib Library appeared first on Indian AI Production.

]]>
Python Matplotlib Tutorial

After complication of python NumPy Tutorial and python pandas tutorial. Now, we jump on the python matplotlib tutorial to become a master in it.

What is python matplotlib?

Matplotlib is a 2D and 3D graph plotting python library. It also supports to create animations and images. This is an advanced part of python matplotlib

Using python matplotlib, you can draw a different graph like below:

Other topics:

Python Matplotlib Tutorial

Why use matplotlib?

As a machine learning engineer or data scientist, data analysis is a part of model development.  Looking numeric data, you can’t get correct insights. So the best way to plot a graph using that data and take a decision for further process. Data visualization is a process take after the data cleaning.

History of matplotlib

The American neurologist John D. Hunter (1968 – 2012), wanted to draw some graph regarding their project. This was the main reason to develop matplotlib python graph plotting library. The matplotlib has written in the Python programming language. As initially, It had been released in 2003. Now, matplotlib is the popular graph plotting library.

For more details, jump on the official site of matplotlib.

John D. Hunter
John D. Hunter

 

Dependency of Matplotlib

The matplotlib is depended on some third-party python library like NumPy.

Download and Install Matplotlib

The matplotlib installation process is very simple. If you are using Anaconda Navigator, then no need to install matplotlib. If you are using Python idle, PyCharm, Sublime Text, etc, then follow the below steps.

Open the command prompt or terminal and enter

pip install matplotlib

and press Enter key to download and install matplotlib. The pip is a package, which installs the matplotlib python library.

Importing Matplotlib

For plotting graph, need to import matplotlib in the python file. Here is two way to import matplotlib given below.

from matplotlib import pyplot as plt # importing pyplot module from matplotlib library
# or
import matplotlib.pyplot as plt #  importing pyplot module from 

In the above code, we import the pyplot module from matplotlib for plot the graphs, like histogram, bar chart, pie plot, etc.

The official study material for matplotlib

Matplotlib Tutorial – click here

Conclusion

I hope, you followed the python matplotlib tutorial and did practical. I am suggesting to you, try to use all the parameters of each method for a better understanding.

After completion of the matplotlib tutorial jump on python seaborn tutorial. It is advance python data visualization library build on top of the matplotlib.

The post Python Matplotlib Tutorial – Mastery in Matplotlib Library appeared first on Indian AI Production.

]]>
https://indianaiproduction.com/python-matplotlib-tutorial/feed/ 0 438