Jovian
⭐️
Sign In
In [5]:
from matplotlib import pyplot as plt
In [6]:
import numpy as np
In [7]:
%matplotlib inline

Line plot

In [8]:
x = np.arange(0, 2 * np.pi, 0.2)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Notebook Image

Subplots

In [9]:
import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# grid height 2 , width 1
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2) # grid height 2 , width 1 
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()
Notebook Image
In [10]:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1 , 100 , 30 ,dtype = int ) # will give 30 points between 1 and 100 , by default dtype is float we can set it to any numerical data types
print(x)
y = x * 2 # generate an array 'y' with double the 'x' values
print(y)
plt.plot(x,y)
plt.title("Simple Plot")
plt.xlabel("30 values between 1 to 100")
plt.ylabel("Double the x values")

[ 1 4 7 11 14 18 21 24 28 31 35 38 41 45 48 52 55 59 62 65 69 72 76 79 82 86 89 93 96 100] [ 2 8 14 22 28 36 42 48 56 62 70 76 82 90 96 104 110 118 124 130 138 144 152 158 164 172 178 186 192 200]
Out[10]:
Text(0, 0.5, 'Double the x values')
Notebook Image
In [11]:
plt.subplot(1,2,1)  # 1 row , 2 columns and plot position is 1st column
plt.plot(x,y,'red')
plt.subplot(1,2,2) # 1 row , 2 columns and plot position is 2nd column
plt.plot(y,x,'green')
Out[11]:
[<matplotlib.lines.Line2D at 0x1e7946e4860>]
Notebook Image
In [12]:
fig = plt.figure()
axs = fig.add_axes([0.1,0.4,0.7,1])
axs.plot(x,y, 'blue')
axs.set_xlabel('X')
axs.set_ylabel('Y')
axs.set_title('Our Fig Title')
fig.savefig('save_fig.png',bbox_inches='tight')
Notebook Image

Histogram

In [13]:
a = np.random.randn(100) # Array of defined shape, filled with random floating-point samples from 
# the standard normal distribution.
plt.hist(a,edgecolor = 'brown', facecolor = 'orange') # we can change facecolor and edgecolor as we like
Out[13]:
(array([ 3.,  6.,  3., 21., 17., 17., 15.,  9.,  4.,  5.]),
 array([-2.50937549, -2.03569459, -1.56201368, -1.08833278, -0.61465188,
        -0.14097098,  0.33270993,  0.80639083,  1.28007173,  1.75375264,
         2.22743354]),
 <a list of 10 Patch objects>)
Notebook Image
In [14]:
import pandas as pd
data = pd.read_csv('data.csv') # dataset
data.head() # print the 1st 5 rows of the dataset
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-14-0fab662bcb0a> in <module> 1 import pandas as pd ----> 2 data = pd.read_csv('data.csv') # dataset 3 data.head() # print the 1st 5 rows of the dataset c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision) 683 ) 684 --> 685 return _read(filepath_or_buffer, kwds) 686 687 parser_f.__name__ = name c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 455 456 # Create the parser. --> 457 parser = TextFileReader(fp_or_buf, **kwds) 458 459 if chunksize or iterator: c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds) 893 self.options["has_index_names"] = kwds["has_index_names"] 894 --> 895 self._make_engine(self.engine) 896 897 def close(self): c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine) 1133 def _make_engine(self, engine="c"): 1134 if engine == "c": -> 1135 self._engine = CParserWrapper(self.f, **self.options) 1136 else: 1137 if engine == "python": c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in __init__(self, src, **kwds) 1915 kwds["usecols"] = self.usecols 1916 -> 1917 self._reader = parsers.TextReader(src, **kwds) 1918 self.unnamed_cols = self._reader.unnamed_cols 1919 pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.__cinit__() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._setup_parser_source() FileNotFoundError: [Errno 2] File b'data.csv' does not exist: b'data.csv'
In [ ]:
plt.hist(data['Salary'],edgecolor='brown',facecolor='orange')
plt.show()

Pie Chart

In [ ]:
data1=data.tail(7)
plt.pie(data1['Salary'], 
        labels=data1['Employee Name'])

plt.axis('equal')

plt.show()

In [ ]:
data1=data.tail(7)
plt.pie(data1['Salary'], 
        labels=data1['Employee Name'],autopct='%.2f') # autopct prints the percentage values

plt.axis('equal')

plt.show()
In [ ]:
data1=data.tail(5)
plt.pie(data1['Salary'], 
        labels=data1['Employee Name'],autopct='%.2f') # autopct prints the percentage values

plt.axis('equal') #plots with equal axis ratios

plt.show()


In [ ]:
data1=data.head(5)
explode = (0.1, 0.1, 0.1, 0.1, 0.1) # Fragment ratios

plt.pie(data1['Salary'], 
        labels=data1['Employee Name'], 
        autopct='%.2f',
        explode=explode)

plt.axis('equal') #plots with equal axis ratios

plt.show()

Bar plot

In [ ]:
data1=data.head(6)
fig = plt.figure()
axs = fig.add_axes([0,0,2,2])
axs.bar(data1['Employee Name'],data1['Salary'])
plt.show()

Scatter plot

In [ ]:
x = [12,34,53,23,76,45,55,87,60,32]
y = [14,43,40,65,73,22,43,76,37,54]
plt.scatter(x, y, marker='o' , color='black')
In [ ]:
x = [12,34,53,23,76,45,55,87,60,32]
y = [14,43,40,65,73,22,43,76,37,54]
plt.scatter(x, y, marker='^' , color='purple');
In [ ]:
x = [12,34,53,23,76,45,55,87,60,32]
y = [14,43,40,65,73,22,43,76,37,54]
plt.scatter(x, y, marker='_' , color='green');

Box plot

In [ ]:
x=[22,45,23,12,56,77,54,22,66,77,96]
y=[55,34,66,87,21,43,78,54,32,77,90]
z=[45,32,76,43,56,98,98,54,21,33,68]
data2=[x,y,z]
plt.boxplot(data2 ,patch_artist=True, labels=['X','Y','Z']) # patch_artist = true, will fill color in box
plt.show()

Violin plot

In [ ]:
x=[22,45,23,12,56,77,54,22,66,77,96]
y=[55,34,66,87,21,43,78,54,32,77,90]
z=[45,32,76,43,56,98,98,54,21,33,68]
data2=[x,y,z]
fig = plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.violinplot(data2) # patch_artist = true, will fill color in box
plt.show()

Seaborn

Factor plot

In [ ]:
import seaborn as sns
dataset = sns.load_dataset("planets")
print(dataset.head())
name = ['distance', 'Mass']
In [15]:
fp = sns.factorplot("distance",'mass',data=dataset.head() ,kind='bar',palette = 'muted')
fp.set_axis_labels("--------Distance--------" , "--------Mass-------")
plt.show()
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-15-3b10bf275983> in <module> ----> 1 fp = sns.factorplot("distance",'mass',data=dataset.head() ,kind='bar',palette = 'muted') 2 fp.set_axis_labels("--------Distance--------" , "--------Mass-------") 3 plt.show() NameError: name 'sns' is not defined
In [16]:
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
import seaborn as sns
dataset = pd.read_csv("tips.csv")
print(dataset.head())
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-16-fb1b9826ab53> in <module> 3 get_ipython().run_line_magic('matplotlib', 'inline') 4 import seaborn as sns ----> 5 dataset = pd.read_csv("tips.csv") 6 print(dataset.head()) c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision) 683 ) 684 --> 685 return _read(filepath_or_buffer, kwds) 686 687 parser_f.__name__ = name c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 455 456 # Create the parser. --> 457 parser = TextFileReader(fp_or_buf, **kwds) 458 459 if chunksize or iterator: c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds) 893 self.options["has_index_names"] = kwds["has_index_names"] 894 --> 895 self._make_engine(self.engine) 896 897 def close(self): c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in _make_engine(self, engine) 1133 def _make_engine(self, engine="c"): 1134 if engine == "c": -> 1135 self._engine = CParserWrapper(self.f, **self.options) 1136 else: 1137 if engine == "python": c:\users\inker_fseai_sys1\appdata\local\programs\python\python36\lib\site-packages\pandas\io\parsers.py in __init__(self, src, **kwds) 1915 kwds["usecols"] = self.usecols 1916 -> 1917 self._reader = parsers.TextReader(src, **kwds) 1918 self.unnamed_cols = self._reader.unnamed_cols 1919 pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.__cinit__() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._setup_parser_source() FileNotFoundError: [Errno 2] File b'tips.csv' does not exist: b'tips.csv'
In [ ]:
x = dataset['Salary'].head()
y = dataset['orbital_period'].head()

sns.relplot(x,y,data = dataset)
In [39]:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(15)

# Syntax : plot(x, y, color='green', marker='o', linestyle='dashed'), where x and y are coordinates

plt.plot(x, x , color = 'black' , marker = 'o' , linestyle = 'dashed')
plt.plot(x, 2 * x , 'bo')  # plot with color blue and marked 'o'
plt.plot(x, 3 * x , '+r') # plot with color red and marker '+'
plt.plot(x, 4 * x , '^g') # plot with color green and marker '^'
plt.plot(x, 6 * x , '--b') # plot with color blue and marker '--'
plt.plot(x, 7 * x)
plt.plot(x, 8 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x', 'y = 6x', 'y = 7x', 'y = 8x'], loc='upper left') # legend will appear on the top left of the figure.

plt.show()
Notebook Image
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: