June 20, 2019

Python matplotlib package

mat plot lib Package in Python


>>> import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticket as mticker
% matplotlib inline # to print within notebook
% matplotlib notebook

Python plotting with matplotlib package

plt.plot([1, 2, 3, 4])
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
plt.plot(x, y, linewidth=2.0)
plt.plot(x, y, label="First Graph")
line, = plt.plot(x, y, '-')
lines = plt.plot(x1, y1, x2, y2)
ax1.plot([],[],linewidth=5, label='gain', color='g', alpha=0.5)
plot(x, y, 'bo')
plot(y, 'r+')
plt.plot(x, y, 'r-', x, y**2, 'b+', x, y**3, 'g^')
plot(x1, y1, x2, y2, antialiased=False)
plot(x, y, color='green', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=12)
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
_ = plt.plot(x, y, marker='.', linestyle='none')

matplotlib.pyplot.plot_date(x, y, fmt='o', tz=None, xdate=True, ydate=False, hold=None, data=None, **kwargs)
plt.plot_date(date, y,'-', label='price')
matplotlib.pyplot.plotfile(fname, cols=(0, ), plotfuncs=None, comments='#', skiprows=0, checkrows=5, delimiter=', ', names=None, subplots=True, newfig=True, **kwargs)
plotfile(fname, (0, 1, 3))
plotfile(fname, ('date', 'volume', 'adj_close'), plotfuncs={'volume': 'semilogy'})

plt.show()
plt.clf()
plt.cla()
plt.axis([0, 6, 0, 20])
plt.axis('off')
plt.axis('equal')
plt.axis('square')
plt.axis('tight')
plt.axis((1947, 1997, 0, 600))
plt.xlim((1947, 2019))
plt.xlim([20, 80])
plt.ylim([200, 800])
plt.ylim((0, 1000))
plt.axes([0.05, 0.05, 0.45, 092])

line.set_antialiased(False)
plt.setp(lines, color='r', linewidth=2.0, linestyle='--')
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
plt.figure(1)
fig = plt.figure(figsize=(6, 6))
fig = plt.figure(1, figsize=(4, 3))
plt.figure(num=None, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k')
plt.xlabel('Smarts')
t = plt.xlabel('my data', fontsize=14, color='red')
plt.ylabel('some numbers')
plt.title('Histogram of IQ')
plt.title('Degrees awarded to women (1990-2010)\nComputer Science (red)\nPhysical Sciences (blue)')

plt.text(1550, 71, 'India')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.text(date[10], closep[2], 'High Stock price')
font_dict = {'family':'serif', 'color':'darkred','size':15}
plt.text(date[4], closep[1], 'Stock price', fontdict=font_dict)
plt.text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
plt.text(0.5, 0.5, 'matplotlib', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)

plt.grid(True)
ax1.grid(True, color='g', linestyle='-', linewidth=5)

annotate function used to annotate the point xy with text.
plt.annotate('setosa', xy=(5.0, 3.5))
plt.annotate('virginica', xy=(7.2, 3.6), xytext=(4.3, 4.0), arrowprops={'color':'red'})
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05),)
ax1.annotate('Highest price',(date[11], highp[11]), xytext=(0.8, 0.9), textcoords='axes fraction')
ax1.annotate('Lowest price',(date[3], highp[3]), xytext=(0.8, 0.9), textcoords='axes fraction', arrowprops=dict(facecolor='grey', color='grey'))

bbox_props=dict(boxstyle='round', fc='g', ec='c', lw=1)
bbox_props=dict(boxstyle='larrow', fc='r', ec='k', lw=1)
ax1.annotate(str(closep[-1]), (date[-1], closep[-1]), xytext=(date[-1]+4, closep[-1]), bbox=bbox_props)
plt.ylim(-2, 2)
plt.xscale('log')
plt.yscale('log')
plt.yscale('symlog', linthreshy=0.01)

plt.bar(x, y, label="First Bar Graph")
plt.bar(x, y, label="First Bar Graph", color='blue')
plt.bar(x, y, label="First Bar Graph", color='r')

Histograms by Python matplotlib package
plt.hist(life_exp) # default bins 10
plt.hist(user_dcs, bins=20)
plt.hist(ages, buckets, histtype='bar', rwidth=0.8)
_ = plt.hist(df['dem_share'])
_ = plt.hist(df['dem_share'], bins=bin_list)
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
_ = plt.hist(inter_nohitter_time, bins=50, normed=True, histtype='step')

Scatter plots by Python matplotlib package
plt.scatter(df['Sales'], df['Profit'])
plt.scatter(x, y, label='scattered graph', color='r')
plt.scatter(x2, y2, label='scattered graph', color='y', s=95, marker='*')
plt.scatter(gdp_cap, life_exp, s = pop)
plt.scatter(x = gdp_cap, y = life_exp, s = np.array(pop) * 2, c = col, alpha=0.8)
plt.scatter(ven_len, ver_wid, marker='o', color='green', label='versi color')
plt.scatter(centroids_x, centroids_y, marker='D', s=50)
plt.scatter(X, Y, s=80, c='green', marker='X')

plt.stackplot(days, sleeping, eating, working, playing, color=['m', 'c', 'r', 'k'])

plt.pie(slices, labels=activities, colors=cols)
plt.pie(slices, labels=activities, colors=cols, startangle=90, shadow=True, explode=(0, 0.1, 0, 0 ))
plt.pie(slices, labels=activities, startangle=30, explode=(0, 0.1, 0, 0), autopct='%1.1f%%')

plt.subplot(num_rows, num_cols, subplot_number)
plt.subplot(211)
plt.subplot(2, 2, 4)
plt.subplot(1, 2, 1)
plt.subplots_adjust(top=0.8)
plt.subplots_adjust(left=0.09, bottom=0.16, right=0.94, top=0.95, wspace=0.2, hspace=0)
fig=plot.figure()
fig.add_subplot(1, 1, 1)
ax2=fig.add_subplot(212)
ax = fig.add_subplot(1, 1, 1, axisbg = 'black')
x,y=create_plots()
ax1=plot.subplot2grid((1, 1),(0, 0))
ax1=plot.subplot2grid((6, 1),(0, 0), rowspan=2, colspan=1)
ax1.xaxis.label.set_color('c')
ax1.yaxis.label.set_color('r')
plt.xticks([0, 2, 4, 6, 8])
plt.xticks([0, 2, 4, 6, 8], ['0','2B','4B','6B','8B'])
ax1.set_xticks([10, 20, 30, 40])
ax1.set_yticks([0, 25, 50, 75])
plt.yticks([1990, 2000, 2010, 2020])
ax1.yticks( arange(12), calendar.month_name[1:13], rotation=45 )
plt.yticks([0,1,2], ["one", "two", "three"])
ax1.fill_between(date, closep, 0)
ax1.fill_between(date, closep, 30, alpha=0.3)
ax1.fill_between(date, closep, closep[2], where(closep>closep[1]), facecolor='g', alpha=0.5)
for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45)
ax1.spines['left'].set_color('c')
ax1.spines['right'].set_color('r')
ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_linewidth(5)
ax1.tick_params(axis='x', colors='#f06215')
ax1.axhline(closep[1], color='k', linewidth=5)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))

legend function is used places a legend on the axes.
plt.legend(digits.target_names, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.legend(loc='upper right')
plt.legend(loc='center left')
plt.legend(loc='lower center')
plt.legend(loc='best')
plt.legend(loc=8)
plt.legend(('setosa', 'versicolor', 'virginica'), loc='lower right')

image = plt.imread("number.png")
print(type(image))

imshow function, in matplotlib package, is used display an image on the axes.
plt.imshow(image)
ax.imshow(clf.cluster_centers_[i].reshape((8, 8)), cmap=plt.cm.binary)
plt.imshow(digits.images[1010], cmap=plt.cm.gray_r, interpolation='nearest')
plt.imshow(im_sq, cmap='Greys', interpolation='nearest')
imgplot = plt.imshow(image)
imgplot.set_cmap('gray')

suptitle is a matplotlib function used to add a centered title to the figure.
fig.suptitle('this is the figure title', fontsize=12)
fig.suptitle('Cluster Center Images', fontsize=14, fontweight='bold')

colors = plt.cm.Spectral(np.linspace(0, 1, len(set(k_means_labels))))
plt.colorbar()

plt.matshow(ranking, cmap=plt.cm.Blues)

from matplotlib.finance import candlestick_ohlc
candlestick_ohlc(ax1, ohlc_var)
candlestick_ohlc(ax1, ohlc_var, width=0.4, colorup='#77de88', colordown='#11cc66')

from matplotlib import style
style.use('ggplot')
style.use('fivethirtyeight')
style.use('dark_background')
plt.style.use('seaborn-deep')
plt.style.use('classic')
print (plt.style.available) # will print styles
print (plt.__file__) # will print matplotlib library path

import matplotlib.animation as animation
ani=animation.FuncAnimation(fig, animate, interval=1000)

import matplotlib.patches as mpatches
green_line = mpatches.Patch(color='red', label='Data Points')

from matplotlib_venn import venn2
_ = venn2(subsets = (3, 2, 1))

Python plotting with plotly, mpl_toolkits, geoplotlib, pylab packages

import plotly
plotly.__version__

matplotlib (MPL) toolkits package
>>> from mpl_toolkits import mplot3d
ax = plt.axes(projection='3d')
>>> from mpl_toolkits.mplot3d import Axes3D
>>> ax = Axes3D(fig)
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float))
ax.scatter(df_train_pca[:,2], df_train_pca[:,0], df_train_pca[:,1], c=y_train.map({0:'green',1:'red'}))
>>> ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet)
>>> ax.plot_surface(x, y, z, cmpa='viridis')
ax.view_init(30, 180)

import geoplotlib
geoplotlib.dot(data)
geoplotlib.show()
cmap = ColorMap('Blues', alpha=255, levels=10)
geoplotlib.geojson('data/gz_2010_us_050_00_20m.json', fill=False, color=[255, 255, 255, 64])
geoplotlib.set_bbox(BoundingBox.USA)
geoplotlib.hist(data, colorscale='sqrt', binsize=8)
geoplotlib.set_smoothing(True)
geoplotlib.shapefiles('data/dk_kommune/dk_kommune', f_tooltip=lambda attr: attr['STEDNAVN'], color=[0, 0, 255])

import pylab as pl
pl.hist(data)
pl.xlabel('data')
pl.show()

Related Python Articles: nltk Package & NLP in Python  Python Online Quiz and Answers


No comments:

Post a Comment