Facebook Twitter Instagram
    Return ScriptReturn Script
    • Home
    • Jobs
    • OOPs concept
    • Blog
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About Us
    • Contact us
    Return ScriptReturn Script
    Knowledge

    Data Visualization using Matplotlib

    Return ScriptBy Return ScriptNovember 23, 2021Updated:April 25, 2022No Comments6 Mins Read

    Data visualization is one of the most important task in the field of machine learning and data science. In this article we will learn about different kind of data visualizations like static, animated and interactive using Matplotlib. Matplotlib is one of the most popular library of python for visualization task, you can get Matplotlib documentation from here.

    How to install Matplotlib

    It is very easy to install Matplotlib on your devices, you can just type the following command in your terminal then installing process will run.

    pip install matplotlib

    You can import this library by using following code.

    import matplotlib.pyplot as plt

    We have to use Matplotlib word many times while doing visualization so, instead to write it every time we import as plt

    Line Plot

    Visualized data in the form of line is one of the easiest task. For line plot you just need equal number of X and Y axis data. The data set need to be in list format, you can use NumPy array tuples etc. you can learn about different data type used in python from here. plot() method is used for plotting a line graph and the graph is only appeared when you call show method from Matplotlib. Following code shows how we plot line graph in python.

    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]
    temperature1 = [39,39.4,40,40.7,41,42.5,43.5,44,44.9,44,45,45.1,46,47,46]
    plt.plot(days,temperature)
    plt.show()
    Basic line plot

    You can give a title for the plot and label to the X and Y axis. Additionally plot() has many parameter example color, linewidth, linestyle etc,. we can use some of this parameter to make above graph meaningful and attractive.

    plt.plot(days, temperature, color = "g", marker = "*", linestyle= "--", linewidth = 0.5,
            markersize = 10)
    plt.title("kathmandu Temperature",fontsize=20) # define title of figure
    plt.xlabel('Days',fontsize=15) #define x label
    plt.ylabel('temperature', fontsize=15)# define y label
    plt.show()
    Updated line graph

    you can plot multiple line by follow the same pattern of single line graph. Following code shows how can you plot multiple line graph.

    plt.plot(days, temperature, color = "g", marker = "o", linestyle= "--", linewidth = 0.5,
            markersize = 10, label = "chitwan")
    plt.plot(days, temperature1, color = "r", marker = "*", linestyle= "--", linewidth = 0.5,
            markersize = 10,label='kathmandu')
    plt.title("kathmandu Temperature",fontsize=20) # define title of figure
    plt.xlabel('Days',fontsize=15) #define x label
    plt.ylabel('temperature', fontsize=15)# define y label
    plt.legend(loc=4) # define lable of two line
    plt.show()

    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() The plt. hist() method has lots of parameter. following code show how can we create histogram.

    import numpy as np
    import random
    ml_students_age = np.random.randint(18,45, (100))
    py_students_age = np.random.randint(15,40, (100))
    plt.hist(ml_students_age)
    plt.title("ML Students age histograms")
    plt.xlabel("Students age cotegory")
    plt.ylabel("No. Students age")
    plt.show()
    Histogram plot

    Bar Graph

    Bar graph is used to visualize data along with categories. Additionally, in Matplotlib we can create a bar graph by using bar() method.Following code show how can we create a bar graph.

    student=['A','B','C','D','E','F','G','H','I','J']
    score_english=np.random.randint(30,100,10)
    score_math=np.random.randint(40,100,10)
    style.use("ggplot") # return grid
    plt.bar(student,score_english)
    plt.title('English Score Bye Student', fontsize=15)
    plt.ylabel('Total number ')
    plt.show()
    Single Bar Graph

    We can create multiple bar graph in the similar way of single bar graph. Following code shows how can we visualized multiple bar graph.

    plt.figure(figsize=(10,5))
    classes_index = np.arange(len(student))
    width = 0.3
    plt.bar(classes_index, score_english, width , color = "b",
            label ="english score") #visible=False
    plt.bar(classes_index+width, score_math, width , color = "g",
            label =" math score") 
    plt.xticks(classes_index+width , student, rotation = 30)
    plt.title('English Score Bye Student', fontsize=15)
    plt.ylabel('Total number ')
    plt.show()
    Multiple Bar Graph

    Scatter Plot

    Matplot has a built-in function to create scatterplots called scatter(). A scatter plot is a type of plot that shows the data as a collection of points.

    N = 500
    x = np.random.rand(N)
    y = np.random.rand(N)
    colors = (0,0,0)
    plt.scatter(x, y,c=colors)
    plt.title('Scatter plot')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()
    Scatter Plot

    Pie Chart

    In this section , 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 make a chart more attractive.

    classes = ["Python", 'R', 'Machine Learning', 'Artificial Intelligence', 
               'Data Sciece']
    class1_students = [45, 15, 35, 25, 30]
    plt.figure(figsize=(16,6))
    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(loc=1)
    plt.show() # To show pie chart only
    Pie Chart

    Sub Plot

    Sub plot is one of the most important part of visualization. Until yet we just plot a single graph, for multiple graph visualization we need a concept of subplot. With a help of subplot we can create multiple graph in a single place. following code show how can we use subplot in Matplotlib.

    plt.subplot(2,2,1)
    plt.pie([1])
    plt.subplot(2,2,2)
    plt.pie([1,2])
    plt.subplot(2,2,3)
    plt.pie([1,2,3])
    plt.subplot(2,2,4)
    plt.pie([1,2,3,4])
    plt.show()
    Subplot

    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 Section, we are explaining, how to save a figure using matplotlib?

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

    Conclusion

    OK, this is the end of the article I hope you can get a good lesson from what I deliver in this article. I ask forgiveness for any word and behave which are not to be. Thank you for your kind and attention guys. Stay tuned for the next article. if you are searching for a free python course here is a link. If you have any questions regarding this article please feel free to comment below.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email

    Related Posts

    What is artificial intelligence and it’s applications

    April 26, 2022
    Add A Comment

    Leave A Reply Cancel Reply

    Recent Updates

    What is artificial intelligence and it’s applications

    April 26, 2022

    Data Visualization using Matplotlib

    November 23, 2021

    Pandas for Machine learning

    November 23, 2021

    NumPy array for machine leaning

    November 23, 2021

    Oops concepts in python with examples

    September 6, 2021

    Types of Operators in Python

    September 6, 2021

    Python Dictionary

    September 28, 2020
    © 2023 Returnscript.com | All Rights Reserved

    Type above and press Enter to search. Press Esc to cancel.