Matplotlib

  • Matplotlib is a low-level graph plotting library in Python that serves as a visualization utility

  • John D. Hunter created Matplotlib in 2008

  • It is based on Numpy for mathematical calculation

Installation of Matplotlib

# Installation code

! pip install matplotlib

Import Matplotlib

import matplotlib

Checking Matplotlib Version

# The version string is stored under __version__ attribute.
# Two underscore characters are used in __version__

matplotlib.__version__
Output:
3.7.1

Pyplot

# Pyplot is submodule of Matplotlib where maximum utilities lies
# Usually imported as plt alias

import matplotlib.pyplot as plt

# Now we can use plt for everywhere to use Pyplot package

Line Plot

Use of plot() function

  • The plot() function is used to draw points (marker) in a diagram.

  • It takes two parameters for specifying points in the diagram:

    • Parameter 01 : It is an array containing the points on the x-axis(horizontal axis).
    • Parameter 02 : It is an array containing the points on the y-axis(vertical axis).

For Example :

We need to plot a line from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10)

We have to pass two arrays [1, 2, 6, 8] and [3, 8, 1, 10] to the plot function

x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y)
plt.show()

""" We can avoid using plt.show() to display graph for such environment like jupyter notebook, colab etc because these environments have a buit-in functionality to automatically dispaly plots.However, in other environments, such as running a Python script in a terminal or in an IDE like PyCharm, the plt.show() function is necessary to display the plot on the screen.Therefore, while it may seem that the plt.show() function is not required to display a plot in some environments, it is still a good practice to include it in your code to ensure that your code works correctly in all environments."""

Plotting without line

  • To plot only markers(points) , parameter ‘o’ can be used which means rings
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y,'o')
plt.show()

Adding label & title

  • xlabel() & ylabel() functions can be used to set x-axis & y-axis
  • title() function can be used to set title of plot
  • Label & title can be designed by fontdict or straight way as below 3 example
  • font or family works same
  • loc=’left’ or ‘right’ or ‘center’ can be used to set position of label & title. Default is center
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y)
plt.xlabel('x variable',loc='right',size=10,color='g',family='serif')
plt.ylabel('y variable',fontdict={'font':'serif','color':'m','size':10})
plt.title('x vs y',loc='left',fontdict={'family':'serif','color':'r','size':20})

Default X-Points

  • If specify only y-values or one list , x-values will get default values 0,1,2,3 & so on depending on y-values
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(y)

plt.plot(x)  # although these are x-values , plot() will consider these as y-values & index 0,1,2... for x-values

plt.plot([1,2,6,8]) # Any one list , plot() will consider these as y-values & index 0,1,2... for x-values

Matplotlib Markers

  • argument marker can be used to emphasize each point with specified marker o,v,> etc..
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y,marker='D') # marker : >,<,*,d,D etc see in documentation for all

Format Strings (fmt)

  • marker | line | color
  • if anything from above three missing , system will take default option
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y, '^:m') # See documentation( Shift + tab) for other line ref, color ref

Marker Size

  • Argument markersize or shorter version ms to set size marker
x = [1,2,6,8]
y = [3,8,1,10]

#plt.plot(x,y,marker='o',markersize=30) OR below

plt.plot(x,y,marker='o',ms=20)

Marker Color

  • Argument markeredgecolor or mec can be used to set color of markers
  • Argument markerfacecolor or mfc can be used to set color of markers
  • Also hexadecimal color value e.g:#4CAF50 can be used
  • or any of 140 supported color names can be used e.g: hotpink etc..
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y,marker='o',ms=30,mec='g',mfc='hotpink') # Use both the mec and mfc arguments to color the entire marker or any of these

Line Style

  • argument linestyle or ls can be used to change plotted line style
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y,linestyle='dotted') # alternate way for dotted :

plt.plot(x,y,ls='dashed') # alternate way for dashed --  # See in documentation for other styles

Line Color

  • Argument color or c can be used to set color of line
  • Also hexadecimal color value e.g:#4CAF50 can be used
  • or any of 140 supported color names can be used e.g: hotpink etc..
x = [1,2,6,8]
y = [3,8,1,10]

#plt.plot(x,y,color='r') #or

plt.plot(x,y,c='g')  # See in documentation for other color reference

Line Width

  • Argument linewidth or lw can be used to change line width.
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y,linewidth='30') #or below

plt.plot(x,y,lw='15')

Use all above function together for Line plot

x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y,marker='^',ms=20,mec='g',mfc='r',ls=':',c='m',lw='10')

Multiple Lines

  • Several line can be plotted using plt.plot() as required
a = [1,2,6,8]
b = [3,8,1,10]
c = [6,14,5,5]

plt.plot(a,marker='o',ms=10,mec='b',mfc='m',ls='-',c='r',lw='5')

plt.plot(b,marker='^',ms=10,mec='g',mfc='r',ls='-.',c='m',lw='5')

plt.plot(c,marker='d',ms=10,mec='g',mfc='r',ls=':',c='g',lw='5')

Grid Lines to a plot

  • grid() can be used to add grid lines to plot
x = [1,2,6,8]
y = [3,8,1,10]

plt.plot(x,y,marker='o')

plt.grid() # will default value

plt.grid(axis='x') # will show only for x axis

plt.grid(axis='y') # will show only for  y axis

plt.grid(c='r',ls='-.',lw=1) # Change properties similar to label& title

Scatter Plot

  • With Pyplot submodule , scatter( ) function can be used to draw a scatter plot.

  • scatter( ) function plots one dot for each observation.

  • It needs two array of the same length

    1. One array for x-axis
    2. One array for y-axis
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]

plt.scatter(x,y)
plt.xlabel('Age of Car')
plt.ylabel('Speed of car')
plt.title('Comparison between speed & age of car')

Observation from above plot:

  • Newer the car , faster it drives
# Day 01 Record
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,111,86,103,87,94,78,77,85,86]

plt.scatter(x,y)
plt.xlabel('Age of Car')
plt.ylabel('Speed of car')
plt.title('Comparison between speed & age of car')

# Day 02 Record
x = [2,2,8,1,15,8,12,9,7,3,11,4,7,14,12]
y = [100,105,84,105,90,99,90,95,94,100,79,112,91,80,85]
plt.scatter(x, y)
plt.xlabel('Age of Car')
plt.ylabel('Speed of car')
plt.title('Comparison between speed & age of car')

# By default two plots are plotted with different colors with blue & orange

Changing Color of Points

  • Argument color or c can be used to change color of points
x = [2,2,8,1,15,8,12,9,7,3,11,4,7,14,12]
y = [100,105,84,105,90,99,90,95,94,100,79,112,91,80,85]
plt.scatter(x, y , c='m')
plt.xlabel('Age of Car')
plt.ylabel('Speed of car')
plt.title('Comparison between speed & age of car')

Separate color for each dot

colors=["red","green","blue","yellow","pink","black","orange","blue","yellow","purple","beige","brown","gray","cyan","magenta"]

x = [2,2,8,1,15,8,12,9,7,3,11,4,7,14,12]
y = [100,105,84,105,90,99,90,95,94,100,79,112,91,80,85]
plt.scatter(x, y , c=colors)
plt.xlabel('Age of Car')
plt.ylabel('Speed of car')
plt.title('Comparison between speed & age of car')


#Length of colors ,x , y must be same

Color Map

  • A color map is like a list of colors , where each color has a value that ranges from 0 to 100
  • The color map is called ‘viridis’
  • It ranges from 0(purple) to 100( yellow)
  • Argument cmap can be used to get color map, viridis is built-in colormaps available in matplotlib

color_map= [0,100,0,100,0,50,0,50,0,60,0,60,0,70,0]

x1 = [2,2,8,1,15,8,12,9,7,3,11,4,7,14,12]
y1 = [100,105,84,105,90,99,90,95,94,100,79,112,91,80,85]

plt.scatter(x1,y1,c=color_map,cmap='viridis')  #use cmap for color spectram

#plt.scatter(x1,y1,c=[0.5,100,0.5,100,0.9,50,0,50,0,60,0,60,0,70,0])  # no of color should be same as points

plt.xlabel('Age of Car')
plt.ylabel('Speed of car')
plt.title('Comparison between speed & age of car')

plt.colorbar()

Size

  • Dots size can be changed with the argument s.
  • Like colors , sizes should have same length as the array for the x-axis & y-axis
x1 = [2,2,8,1,15,8,12,9,7,3,11,4,7,14,12]
y1 = [100,105,84,105,90,99,90,95,94,100,79,112,91,80,85]
sizes=[100,90,80,70,60,50,40,30,20,19,20,21,22,23,24]
plt.scatter(x1,y1,s=sizes)

Transparency of dots or Alpha

  • The transparency of dots can be adjusted with the alpha argument.
x1 = [2,2,8,1,15,8,12,9,7,3,11,4,7,14,12]
y1 = [100,105,84,105,90,99,90,95,94,100,79,112,91,80,85]
sizes=[100,90,80,70,60,50,40,30,20,19,20,21,22,23,24]
plt.scatter(x1,y1,s=sizes,alpha=0.4) # alpha should be in 0-1 range

Bars Diagram

  • With Pyplot submodule , bar( ) can be used to draw bar graphs.

  • First argument is category & Second argument is values in bar( )

# Vertical Bar

x = ['A','B','C','D']
y = [3,8,1,10]

plt.bar(x,y)

 

# Horizontal Bar

x = ['A','B','C','D']
y = [3,8,1,10]

plt.barh(x,y)

Bar Design ( Color , Width , Height)

  • Color : color should use , default color Blue

  • Width : width should use , default width is 0.8

  • Height : height should use for horizontal bar.default height as the y-values you provide in the function call

# Vertical bar with width

x = ['A','B','C','D']
y = [3,8,1,10]

plt.bar(x,y,color='green',width=0.5)
plt.bar()

# Horizontal bar with height

x = ['A','B','C','D']
y = [3,8,1,10]

plt.barh(x,y,color='green',height=0.5)

Histogram

  • Histogram shows frequency distributions.

  • It shows number of observations within each given interval.

  • hist( ) function use to create histograms.

# Create array for creating histogram
import numpy as np
x= np.random.normal(50,5,100)

# Creating histogram

plt.hist(x)

# Use of color,bins & width

plt.hist(x,color='red',edgecolor='g',rwidth=0.8,bins=20)

Pie Charts

  • With Pyplot , pie( ) can be used to draw pie charts

  • Pie chart draws one piece (called a wedge) for each value in the array

  • The value divided by the sum of all values: x/sum(x)

  • By default the plotting of the first wedge starts from the x-axis and moves counterclockwise:

# Creating Pie plot

y = [35, 25, 25, 15]

plt.pie(y)

# Adding label to Pie plot & perchantage

Category = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y,labels=Category,autopct='%0.0f')

# Change Start Angle


Category = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y,labels=Category, startangle=90) # default angle 0

 

# Set explode to wedges to stand out

Category = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y,labels=Category, explode=[0,0.3,0,0]) # values of explode must be same as category

# Add shadow

Category = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y,labels=Category, explode=[0,0.3,0,0],shadow=True)

# Change Color

Category = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y,labels=Category,colors=['g','m','b','k'])

# Add legend

Category = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y,labels=Category,colors=['g','m','b','k'])

plt.legend()

# Add legend with header

Category = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y,labels=Category,colors=['g','m','b','k'])

plt.legend(title='Fruits')

Note:

  • Bar plot is for bivariate ( categorical & numerical )

  • Histogram is for univariate , break data in several range

Save any figure

# Use .savefig() to save any figure

plt.pie(y,labels=Category,colors=['g','m','b','k'])

plt.savefig('Pie_fruits.png')

Display multiple plots

Use of subplot( )

  • Using subplot() , multiple plots can be placed in one figure

  • subplot() function takes three arguments that describe layout of the figure

    1. First argument represents rows in layout.

    2. Second argument represents columns in the layout.

    3. Third argument represents index of the current plot.

      plt.subplot(req rows , req columns, plot number)

    4. Title, label can be added as mentioned earlier topics

    5. suptitle( ), supertitle can be used to set name for entire figure

w = [9,7,8,10]
x = [0,1,2,3]
y = [3,8,1,10]
z = [10,23,4,10]

plt.subplot(2,2,1)
plt.plot(x,z)
plt.title('x vs z')

plt.subplot(2,2,2)
# no plot kept intentionally

plt.subplot(2,2,3)
plt.plot(x,y)
plt.xlabel('x variable')
plt.ylabel('y variable')
plt.title('x vs y')

plt.subplot(2,2,4)
plt.plot(x,w)
plt.xlabel('x variable')
plt.ylabel('w variable')
plt.title('x vs w')

plt.suptitle('My Plot')

Use of subplots( ) function

  • Write as fig, ax = plt.subplots(nrows,ncols) .

  • It is different than subplot( )

  • For each axis , ax[row index][column index]

a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]

fig,ax = plt.subplots(3,3)

ax[0][0].plot(a,b,color = 'red')

ax[2][0].plot(a,b,color = 'green')

ax[0][1].plot(a,b,color = 'm')

ax[1][2].plot(a,b,color = 'k')

ax[2][2].plot(a,b,color = 'c')

Use of matplotlib.pyplot.figure()

  • used to create a new figure.
  • Syntax: matplotlib.pyplot.figure(num=None,figsize=None,dpi=None,facecolor=None, edgecolor=None,frameon=True,FigureClass=, clear=False, **kwargs)
  • Parameters: This method accept the following parameters that are described below:
    • num : This parameter is provided, and a figure with this id already exists.
    • figsize(float, float): These parameter are the width, height in inches.
    • dpi : This parameter is the resolution of the figure.
    • facecolor : This parameter is the background color.
    • edgecolor : This parameter is the border color.
    • frameon : This parameter suppress drawing the figure frame.
    • FigureClass : This parameter use a custom Figure instance.
    • clear : This parameter if True and the figure already exists, then it is cleared.
# plt is used instead of matplotlib.pyplot

plt.figure(figsize=(10,15),facecolor='cyan',edgecolor='red')

Output:
<Figure size 1000x1500 with 0 Axes>
<Figure size 1000x1500 with 0 Axes>

Use of add_axes

  • Use to add an Axes to a Figure manually
  • The syntax for add_axes() is as follows:

         add_axes(rectangle, projection=None, polar=False, **kwargs)

  • first arg to move horizontally , second arg to move vertically ,third arg to change width, fourth arg to change height
  • rectangle parameter specifies the position and size of the Axes within the Figure, specified as [left, bottom, width, height] values in Figure coordinates (ranging from 0 to 1).
  • The projection parameter specifies the type of projection to use (e.g., ‘polar’ for a polar coordinate system), and the polar parameter can be set to True to create a polar Axes.
fig=plt.figure(figsize=(5,5),facecolor='white',edgecolor='cyan')

ax1=fig.add_axes([0.4,0.4,0.5,0.5])  # first arg to move horizontally , second arg to move vertically ,third arg to change width, forth arg to change height
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax1.plot(a,b)
ax1.set_xlabel('a')
ax1.set_ylabel('b')
ax1.set_title('a vs b')


ax2=fig.add_axes([0.4,1.08,0.5,0.5])
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax2.bar(a,b)
ax2.set_xlabel('a')
ax2.set_ylabel('b')
ax2.set_title('a vs b')

ax3=fig.add_axes([1.08,0.4,0.5,0.5])
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax3.scatter(a,b)
ax3.set_xlabel('a')
ax3.set_ylabel('b')
ax3.set_title('a vs b')

ax4=fig.add_axes([1.08,1.08,0.5,0.5])
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax4.hist(b)
ax4.set_xlabel('a')
ax4.set_ylabel('b')
ax4.set_title('a vs b')

fig=plt.figure(figsize=(5,5),facecolor='white',edgecolor='cyan')

ax1=fig.add_axes([0.4,0.4,0.5,0.5])
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax1.plot(a,b)
ax1.set_xlabel('a')
ax1.set_ylabel('b')
ax1.set_title('a vs b')


ax2=fig.add_axes([0.4,1.08,0.5,0.5])
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax2.bar(a,b)
ax2.set_xlabel('a')
ax2.set_ylabel('b')
ax2.set_title('a vs b')

ax3=fig.add_axes([1.08,0.4,0.5,0.5])
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax3.scatter(a,b)
ax3.set_xlabel('a')
ax3.set_ylabel('b')
ax3.set_title('a vs b')

ax4=fig.add_axes([1.08,1.08,1,1]) # first arg to move horizontally , second arg to move vertically ,third arg to change width, forth arg to change height
a = [2,4,6,8,10,12,14,16,18,20]
b = [2,5,33,12,29,12,17,11,25,29]
ax4.hist(b)
ax4.set_xlabel('a')
ax4.set_ylabel('b')
ax4.set_title('ax4')

Create 3d plot

#option 01
import matplotlib.pyplot as plt
import numpy as np

# Creating input data

x = np.random.rand(10)
y = np.random.rand(10)
z = np.random.rand(10)

# Create a 3D scatter plot
fig = plt.figure()


ax = fig.add_subplot(1,1,1, projection='3d')
ax.scatter(x, y, z,c=z,cmap='viridis')

# Set labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Scatter Plot')

# Display the plot
plt.show()

#option 02
import matplotlib.pyplot as plt
import numpy as np

# Creating input data

x = np.random.rand(10)
y = np.random.rand(10)
z = np.random.rand(10)

# Create a 3D scatter plot
fig = plt.figure()

ax = plt.axes(projection='3d')
ax.scatter3D(x,y,z,c=z, cmap='viridis')

# Set labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Scatter Plot')

# Display the plot
plt.show()

How to load & show image

 

import matplotlib.pyplot as plt
import matplotlib.image as img

my_image = img.imread('/content/my_photo.jpg')

plt.imshow(my_image)

plt.axis('off')

Treemap

  • Install squarify library in Python is used for creating treemaps, which are a way to visualize hierarchical data using nested rectangles. 
! pip install squarify
import matplotlib.pyplot as plt
import squarify  # You might need to install this library using: pip install squarify

# Example data for the treemap
categories = ["Category A", "Category B", "Category C", "Category D"]
values = [40, 25, 20, 15]  # Values representing the proportion of each category

# Create a squarify treemap
squarify.plot(sizes=values, label=categories, alpha=0.7) # alpha is for transparency( range 0 to 1)

# Add labels and title
plt.axis('off')  # Turn off axis labels and ticks
plt.title("Treemap Example")

# Show the treemap
plt.show()

Area Chart

import matplotlib.pyplot as plt

# Example data for the area chart
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016]
category_a = [25, 40, 50, 45, 60, 70, 80]
category_b = [10, 20, 30, 35, 40, 50, 60]

# Create an area chart
plt.stackplot(years, category_a, category_b, labels=['Category A', 'Category B'], alpha=0.6)

# Add labels and title
plt.xlabel('Years')
plt.ylabel('Values')
plt.title('Area Chart Example')
plt.legend(loc='upper left')

# Show the area chart
plt.tight_layout()
plt.show()

Candlestick chart

Iinstall mplfinance which is a Python library designed for creating financial market charts, such as candlestick charts, OHLC (Open-High-Low-Close) charts, and other types of financial visualizations.

import pandas as pd
import mplfinance as mpf

# Example data for candlestick chart
data = {'Open': [100, 105, 110, 115, 120],
        'High': [115, 120, 125, 130, 125],
        'Low': [95, 100, 105, 110, 115],
        'Close': [110, 115, 120, 125, 110]}
index = ['2023-07-01', '2023-07-02', '2023-07-03', '2023-07-04', '2023-07-05']

# Convert index to DatetimeIndex
index = pd.to_datetime(index)
df = pd.DataFrame(data, index=index)

# Create a candlestick chart using mplfinance
mpf.plot(df, type='candle', title='Candlestick Chart Example', ylabel='Price')


Network graph

  • Install networkx which is a powerful Python library used for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks.
! pip install networkx
import networkx as nx
import matplotlib.pyplot as plt

# Create a graph
G = nx.Graph()

# Add nodes
G.add_node('A')
G.add_node('B')
G.add_node('C')
G.add_node('D')

# Add edges
G.add_edge('A', 'B')
G.add_edge('A', 'C')
G.add_edge('B', 'C')
G.add_edge('C', 'D')

# Draw the network graph
pos = nx.spring_layout(G)  # Position nodes using the spring layout algorithm
nx.draw(G, pos, with_labels=True, node_size=1000, node_color='lightblue', font_size=10, font_color='black', font_weight='bold', edge_color='gray')

# Show the network graph
plt.title('Network Graph Example')
plt.show()

Word Counts Plot

import matplotlib.pyplot as plt

def word_count(text):
    words = text.split()
    word_freq = {}

    for word in words:
        word = word.lower()
        if word in word_freq:
            word_freq[word] += 1
        else:
            word_freq[word] = 1

    return word_freq

# Example text
text = "This is an example sentence. This sentence is just an example."

word_frequencies = word_count(text)

# Extract words and counts for plotting
words = list(word_frequencies.keys())
counts = list(word_frequencies.values())

# Create a bar plot
plt.bar(words, counts, color='skyblue')

# Customize the plot
plt.xlabel('Words')
plt.ylabel('Counts')
plt.title('Word Counts Plot')
plt.xticks(rotation=45, ha='right')

# Show the plot
plt.tight_layout()
plt.show()

textblob matplotlib

TextBlob is a Python library for processing textual data, providing a simple API for common natural language processing (NLP) tasks such as part-of-speech tagging, noun phrase extraction, sentiment analysis, classification, translation, and more. When combined with matplotlib, you can visualize various text analytics results such as sentiment analysis over time.

! pip install textblob matplotlib
import matplotlib.pyplot as plt
from textblob import TextBlob

# Example text data
text_data = [
    "I love this product! It's amazing.",
    "The service was terrible. I'm very disappointed.",
    "The weather is nice today.",
    "This movie was boring. I wouldn't recommend it.",
    "I'm feeling happy and excited.",
]

# Analyze sentiment and calculate polarity for each text
sentiments = []
polarities = []

for text in text_data:
    analysis = TextBlob(text)
    sentiment = analysis.sentiment.polarity
    sentiments.append(sentiment)
    polarities.append("Positive" if sentiment > 0 else "Negative" if sentiment < 0 else "Neutral")

# Create a sentiment analysis plot
plt.figure(figsize=(8, 6))
plt.barh(range(len(text_data)), sentiments, color='skyblue')
plt.yticks(range(len(text_data)), text_data, fontsize=10)
plt.xlabel('Sentiment Polarity')
plt.ylabel('Text')
plt.title('Sentiment Analysis Plot')
plt.axvline(x=0, color='gray', linestyle='--')
plt.tight_layout()

# Annotate with polarities
for i, polarity in enumerate(polarities):
    plt.text(0.05, i, polarity, va='center', fontsize=10, color='black', fontweight='bold')

# Show the plot
plt.show()

Text Visualization to see word frequency

  • Install wordcloud which is library in Python used to generate word clouds, which are visual representations of text data where the size of each word indicates its frequency or importance. 
from wordcloud import WordCloud
import matplotlib.pyplot as plt

text = 'I have collected some reviews from my friends about movie Pushpa, Sundar reviews is this movie is about attitude ,Samia loves this movie, uzzal loves this movie wheras gagana hate this movie '

wordcloud =WordCloud().generate(text)

plt.figure(figsize=(5,8))
plt.imshow(wordcloud)
plt.axis('off')
plt.title('Text frequency visualization')

Register

Login here

Forgot your password?

ads

ads

I am an enthusiastic advocate for the transformative power of data in the fashion realm. Armed with a strong background in data science, I am committed to revolutionizing the industry by unlocking valuable insights, optimizing processes, and fostering a data-centric culture that propels fashion businesses into a successful and forward-thinking future. - Masud Rana, Certified Data Scientist, IABAC

© Data4Fashion 2023-2024

Developed by: Behostweb.com

Please accept cookies
Accept All Cookies