The Wayback Machine - https://web.archive.org/web/20240927161504/https://www.geeksforgeeks.org/plot-multiple-separate-graphs-for-same-data-from-one-python-script/
Open In App

Plot multiple separate graphs for same data from one Python script

Last Updated : 13 Sep, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

It is very easy to plot different kinds of maps and plots of different data using Python. One such useful library in Python is Matplotlib which is very useful for creating different types of plots using the same data.

The easiest way to install Matplotlib is by using the pip command in the command-line as shown below:

pip install matplotlib

Also, we use numpy and pandas libraries for creating and using the data sets. Therefore, installing numpy and pandas library can also be done using pip command in command-line.

pip install numpy 
pip install pandas

To make plots creative and easy to find the located data inside the graph we use the plotly and cufflinks libraries. To use these libraries the method of installation is also the same as above mentioned libraries. 

pip install chart_studio.plotly
pip install cufflinks

In this article, we will create a Plotter that enables us to create different types of plots using the same data.

In this program, we first give the option for choosing the data set required to plot the graph. There are 3 options available for that using if-elif statements. 

  • Creating random data using 100 rows and 5 columns
  • User input data set with 4 rows and 5 columns
  • Upload the CSV/JSON file

The second step is to decide the plot to be plotted with the entire data set or for specific columns. And lastly, we present different kinds of plotters users want to plot their data and plot the graph accordingly. 

Below is the implementation:

Python3




# importing required libraries
import numpy as np
import pandas as pd
import chart_studio.plotly as pl
import plotly.offline as po
import cufflinks as cf
po.init_notebook_mode(connected = True)
cf.go_offline()
 
# define a function for creating
# data set for plotting graph
def createdata(data):
   
    # creating random data set
    if(data == 1):
        x = np.random.rand(100,5)
        df1 = pd.DataFrame(x, columns = ['A', 'B',
                                        'C', 'D',
                                        'E'])
         
    # creating user data set with input
    elif(data == 2):           
        x = [0, 0, 0, 0, 0]
        r1 = [0, 0, 0, 0, 0]
        r2 = [0, 0, 0, 0, 0]
        r3 = [0, 0, 0, 0, 0]
        r4 = [0, 0, 0, 0, 0]
         
        print('Enter the values for columns')
        i = 0
         
        for i in [0, 1, 2, 3, 4]:
            x[i] = input()
            i = i + 1
        print('Enter the values for first row')
        i = 0
         
        for i in [0, 1, 2, 3, 4]:
            r1[i] = int(input())
            i = i + 1
             
        print('Enter the values for second row')
        i = 0
         
        for i in [0, 1, 2, 3, 4]:
            r2[i] = int(input())
            i = i + 1
             
        print('Enter the values for third row')
        i = 0
         
        for i in [0, 1, 2, 3, 4]:
            r3[i] = int(input())
            i = i + 1
             
        print('Enter the values for fourth row')
        i = 0
         
        for i in [0, 1, 2, 3, 4]:
            r4[i] = int(input())
            i = i + 1
             
        df1 = pd.DataFrame([r1,r2,r3,r4] ,
                           columns = x)
    # creating data set by csv file  
    elif(data == 3):           
        file = input('Enter the file name')
        x = pd.read_csv(file)
        df1 = pd.DataFrame(x)
         
    else:
        print('DataFrame creation failed please' +
              'enter in between 1 to 3 and try again')
         
    return df1
 
# define a function for
# types of plotters
def plotter(plot):
   
    if(plot == 1):
        finalplot = df1.iplot(kind = 'scatter')
         
    elif(plot == 2):
        finalplot = df1.iplot(kind = 'scatter', mode = 'markers',
                              symbol = 'x', colorscale = 'paired')
    elif(plot == 3):
        finalplot = df1.iplot(kind = 'bar')
         
    elif(plot == 4):
        finalplot = df1.iplot(kind = 'hist')
         
    elif(plot == 5):
        finalplot = df1.iplot(kind = 'box')
         
    elif(plot == 6):
        finalplot = df1.iplot(kind = 'surface')
         
    else:
        finalplot = print('Select only between 1 to 7')
         
    return finalplot
 
# define a function for allowing
# to plot for specific rows and columns
def plotter2(plot):           
   
    col = input('Enter the number of columns you' +
                'want to plot by selecting only 1 , 2 or 3')
     
    col = int(col)
     
    if(col==1):
       
        colm = input('Enter the column you want to plot' +
                     'by selecting any column from dataframe head')
        if(plot == 1):
            finalplot = df1[colm].iplot(kind = 'scatter')
             
        elif(plot == 2):
            finalplot = df1[colm].iplot(kind = 'scatter', mode = 'markers',
                                        symbol = 'x', colorscale = 'paired')
        elif(plot == 3):
            finalplot = df1[colm].iplot(kind = 'bar')
             
        elif(plot == 4):
            finalplot = df1[colm].iplot(kind = 'hist')
             
        elif(plot == 5):
            finalplot = df1[colm].iplot(kind = 'box')
             
        elif(plot == 6 or plot == 7):
            finalplot = print('Bubble plot and surface plot require' +
                              'more than one column arguments')
        else:
            finalplot = print('Select only between 1 to 7')
             
    elif(col == 2):
       
        print('Enter the columns you want to plot' +
              'by selecting from dataframe head')
         
        x = input('First column')
        y = input('Second column')
         
        if(plot == 1):
            finalplot = df1[[x,y]].iplot(kind = 'scatter')
             
        elif(plot == 2):
            finalplot = df1[[x,y]].iplot(kind = 'scatter', mode = 'markers',
                                         symbol = 'x', colorscale = 'paired')
        elif(plot == 3):
            finalplot = df1[[x,y]].iplot(kind = 'bar')
             
        elif(plot == 4):
            finalplot = df1[[x,y]].iplot(kind = 'hist')
             
        elif(plot == 5):
            finalplot = df1[[x,y]].iplot(kind = 'box')
             
        elif(plot == 6):
            finalplot = df1[[x,y]].iplot(kind = 'surface')
             
        elif(plot == 7):
            size = input('Please enter the size column for bubble plot')
            finalplot = df1.iplot(kind = 'bubble', x = x,
                                  y = y, size = size)
        else:
            finalplot = print('Select only between 1 to 7')
             
    elif(col == 3):
       
        print('Enter the columns you want to plot')
        x = input('First column')
        y = input('Second column')
        z = input('Third column')
          
        if(plot == 1):
            finalplot = df1[[x,y,z]].iplot(kind = 'scatter')
             
        elif(plot == 2):
            finalplot = df1[[x,y,z]].iplot(kind = 'scatter', mode = 'markers',
                                           symbol = 'x' ,colorscale = 'paired')
        elif(plot == 3):
            finalplot = df1[[x,y,z]].iplot(kind = 'bar')
             
        elif(plot == 4):
            finalplot = df1[[x,y,z]].iplot(kind = 'hist')
             
        elif(plot == 5):
            finalplot = df1[[x,y,z]].iplot(kind = 'box')
             
        elif(plot == 6):
            finalplot = df1[[x,y,z]].iplot(kind = 'surface')
             
        elif(plot == 7):
            size = input('Please enter the size column for bubble plot')
             
            finalplot = df1.iplot(kind = 'bubble', x = x, y = y,
                                  z = z, size = size )
        else:
            finalplot = print('Select only between 1 to 7')
    else:
        finalplot = print('Please enter only 1 , 2 or 3')
    return finalplot
 
# define a main function
# for asking type of plot
# and calling respective function
def main(cat):   
   
    if(cat == 1):
       
        print('Select the type of plot you need to plot by writing 1 to 6')
        print('1.Line plot')
        print('2.Scatter plot')
        print('3.Bar plot')
        print('4.Histogram')
        print('5.Box plot')
        print('6.Surface plot')
        plot = int(input())
        output = plotter(plot)
         
    elif(cat == 2):
       
        print('Select the type of plot you need to plot by writing 1 to 7')
        print('1.Line plot')
        print('2.Scatter plot')
        print('3.Bar plot')
        print('4.Histogram')
        print('5.Box plot')
        print('6.Surface plot')
        print('7.Bubble plot')
        plot = int(input())
        output = plotter2(plot)
         
    else:
        print('Please enter 1 or 2 and try again') 
         
print('Select the type of data you need to plot(By writing 1,2 or 3)')
print('1.Random data with 100 rows and 5 columns')
print('2.Customize dataframe with 5 columns and. 4 rows')
print('3.Upload csv/json/txt file')
 
data = int(input())
df1 = createdata(data)
print('Your DataFrame head is given below check the columns to plot using cufflinks')
 
df1.head()
print('What kind of plot you need , the complete data plot or columns plot')
cat = input('Press 1 for plotting all columns or press 2 for specifying columns to plot')
cat = int(cat)
 
main(cat)


 
 

Output:

 

Scatter plot:

 

 Scatter graph plot

 Scatter graph plot

Histogram plot:

 

Histogram plot

Histogram plot 

Boxplot:

 

Box plot

Boxplot 

 



Similar Reads

Pandas - Plot multiple time series DataFrame into a single plot
In this article, we are going to see how to plot multiple time series Dataframe into single plot. If there are multiple time series in a single DataFrame, you can still use the plot() method to plot a line chart of all the time series. To Plot multiple time series into a single plot first of all we have to ensure that indexes of all the DataFrames
4 min read
Read multiple CSV files into separate DataFrames in Python
Sometimes you might need to read multiple CSV files into separate Pandas DataFrames. Importing CSV files into DataFrames helps you work on the data using Python functionalities for data analysis. In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one CSV file, we can use pd.read_csv() function of
2 min read
Plot Live Graphs using Python Dash and Plotly
Dash is a Python framework built on top of ReactJS, Plotly and Flask. It is used to create interactive web dashboards using just python. Live graphs are particularly necessary for certain applications such as medical tests, stock data, or basically for any kind of data that changes in a very short amount of time where it is not viable to reload eac
4 min read
Plot 2D data on 3D plot in Python
In this article, we will be learning about how to plot 2D data on 3D plot in Python. We will be demonstrating two methods in order to learn the concept. The first method will be using Matplotlib.pyplot.gca() function which is a pyplot module of the matplotlib library. But before that, we need to configure where are we going to create our project an
4 min read
How to plot multiple data columns in a DataFrame?
Python comes with a lot of useful packages such as pandas, matplotlib, numpy, etc. To use DataFrame, we need a Pandas library and to plot columns of a DataFrame, we require matplotlib. Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method. To plot multiple data columns in the single f
3 min read
PyQtGraph - Getting Plot Item from Plot Window
In this article we will see how we can get the plot item of plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and s
2 min read
Time Series Plot or Line plot with Pandas
Prerequisite: Create a Pandas DataFrame from Lists Pandas is an open-source library used for data manipulation and analysis in Python. It is a fast and powerful tool that offers data structures and operations to manipulate numerical tables and time series. Examples of these data manipulation operations include merging, reshaping, selecting, data cl
6 min read
Pandas Scatter Plot – DataFrame.plot.scatter()
A Scatter plot is a type of data visualization technique that shows the relationship between two numerical variables. For plotting to scatter plot using pandas there is DataFrame class and this class has a member called plot. Calling the scatter() method on the plot member draws a plot between two variables or two columns of pandas DataFrame. Synta
2 min read
Run One Python Script From Another in Python
In Python, we can run one file from another using the import statement for integrating functions or modules, exec() function for dynamic code execution, subprocess module for running a script as a separate process, or os.system() function for executing a command to run another Python file within the same process. In this article, we will explore al
5 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python | Convert column to separate elements in list of lists
There are instances in which we might require to extract a particular column of a Matrix and assign its each value as separate entity in list and this generally has a utility in Machine Learning domain. Let's discuss certain ways in which this action can be performed.Method #1 : Using list slicing and list comprehension The functionality of list sl
4 min read
Python | Separate odd and even index elements
Python list are quite popular and no matter what type of field one is coding, one has to deal with lists and its various applications. In this particular article, we discuss ways to separate odd and even indexed elements and its reconstruction join. Let's discuss ways to achieve this. Method #1 : Using Naive methodUsing Naive method, this task can
4 min read
Python | Split and Pass list as separate parameter
With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let's discuss cert
4 min read
Python - Separate first word from String
Sometimes, while working with Python strings, we can have a problem in which we need to separate the first word from the entire string. This can have possible applications in many domains such as day-day and web-development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is the brute force way in which t
7 min read
Python program to separate alphabets and numbers in a string
Given a string containing numbers and alphabets, the task is to write a Python program to separate alphabets and numbers from a string using regular expression. Examples Input: abcd11gdf15hnnn678hh4 Output: 11 15 678 4 abcd gdf hnnn hh Explanation: The string is traversed from left to right and number and alphabets are separated from the given stri
4 min read
Create a plot with Multiple Glyphs using Python Bokeh
In this article, we will be learning about multiple glyphs and also about adding a legend in bokeh. Now bokeh provides us with a variety of glyphs that can be used to represent a point in a plot. Some glyphs are circle, square, asterik, inverted_triangle(), triangle() etc. Installation This module does not come in-built with Python. To install it t
7 min read
How to Plot Multiple DataFrames in Subplots in Python
Plotting multiple dataframes in subplots is a powerful technique in data visualization, especially when comparing trends or patterns across different datasets. This approach allows you to display multiple plots within a single figure, making it easier to analyze relationships and differences between datasets. What Does It Mean to Plot Multiple Data
3 min read
Convert list-like column elements to separate rows in Pandas
A dataframe is a tabular structure where data is arranged in rows and columns. Often while working with real data, columns having list-like elements are encountered. List-like means that the elements are of a form that can be easily converted into a list. In this article, we will see various approaches to convert list-like column elements to separa
3 min read
Spark - Split array to separate column
Apache Spark is a potent big data processing system that can analyze enormous amounts of data concurrently over distributed computer clusters. PySpark is a Python-based interface for Apache Spark. Python programmers may create Spark applications more quickly and easily thanks to PySpark. Method 1: Using The Function Split() In this example first, t
3 min read
How to update a plot on same figure during the loop?
We can use matplotlib to Plot live data with Matplotlib. With the help of matplotlib.pyplot.draw() function we can update the plot on the same figure during the loop. Plotting live data with Matplotlib Using matplotlib.pyplot.draw(), It is used to update a figure that has been changed. It will redraw the current figure. Before this we use figure.io
3 min read
Plot Several Curve Segments on the Same Graph
R is a programming language and software environment for statistical computing and graphics. It is widely used among statisticians and data scientists for developing statistical software and data analysis. R Programming Language is known for its powerful and flexible data visualization capabilities. The base installation of R includes several libra
5 min read
Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib
Prerequisites: PandasMatplotlib In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are
2 min read
How to Plot Multiple Series from a Pandas DataFrame?
In this article, we will discuss how to plot multiple series from a dataframe in pandas. Series is the range of the data that include integer points we cab plot in pandas dataframe by using plot() function Syntax: matplotlib.pyplot(dataframe['column_name']) We can place n number of series and we have to call the show() function to display the plot
2 min read
Plot multiple plots in Matplotlib
Prerequisites: Matplotlib In Matplotlib, we can draw multiple graphs in a single plot in two ways. One is by using subplot() function and other by superimposition of second graph on the first i.e, all graphs will appear on the same plot. We will look into both the ways one by one. Multiple Plots using subplot () FunctionA subplot () function is a w
6 min read
Plot Multiple lines in Matplotlib
In this article, we will learn how to plot multiple lines using matplotlib in Python. Let's discuss some concepts: Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was intr
6 min read
Plot Multinomial and One-vs-Rest Logistic Regression in Scikit Learn
Logistic Regression is a popular classification algorithm that is used to predict the probability of a binary or multi-class target variable. In scikit-learn, there are two types of logistic regression algorithms: Multinomial logistic regression and One-vs-Rest logistic regression. Multinomial logistic regression is used when the target variable ha
4 min read
Python | Visualize graphs generated in NetworkX using Matplotlib
Prerequisites: Generating Graph using Network X, Matplotlib IntroIn this article, we will be discussing how to plot a graph generated by NetworkX in Python using Matplotlib. NetworkX is not a graph visualizing package but basic drawing with Matplotlib is included in the software package. Step 1 : Import networkx and matplotlib.pyplot in the project
3 min read
Visualize Graphs in Python
Prerequisites: Graph Data Structure And Algorithms A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. In this tutorial we are going to visualize undirected Graphs in Python with the help of networkx librar
2 min read
Operations on Graph and Special Graphs using Networkx module | Python
This article shows how to create an undirected Graph. This article continues for other types of Graphs and visualization techniques. The basic Graph operations are as follows: Getting Subgraph from a Graph : Given a Graph, if we are given a subset of its set of nodes, we can create a Subgraph by selecting these nodes and all the edges between them
8 min read
Plotting Various Sounds on Graphs using Python and Matplotlib
In this article, we will explore the way of visualizing sounds waves using Python and Matplotlib. Modules Needed 1. Matplotlib: Install Matplotlib using the below command: pip install matplotlib 2. Numpy: Numpy gets installed automatically installed with Matplotlib. Although, if you face any import error, use the below command to install Numpy pip
3 min read