import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
mu = 100
sigma = 25
fig, (ax0, ax1) = plt.subplots(ncols = 2)
x = mu + sigma * np.random.randn(1000)
ax0.hist(x, 20, normed=1, histtype='stepfilled', facecolor='g', alpha=0.75)
ax0.set_title('Stepfilled histogram')
ax1.hist(x, bins=[100,150, 165, 170, 195], normed=1, histtype='bar', rwidth=0.8)
ax1.set_title('uniquel bins histogram')
plt.tight_layout() #automatically adjust subplot parameters to give specified padding
plt.savefig('histogram.png')
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py:6521: MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead. alternative="'density'", removal="3.1")
x = np.linspace(-2.4, 0.4, 20)
y = x * x + 2 * x + 1
plt.plot(x, y, 'c', linewidth=2.0)
plt.text(-1.5, 1.8, 'y=x^2 + 2*x + 1',
fontsize=14, style='italic')
plt.annotate('minima point', xy=(-1, 0),
xytext=(-1, 0.3), horizontalalignment='center',
verticalalignment='top',
arrowprops=dict(arrowstyle='->',
connectionstyle='arc3'))
plt.savefig('annotate.png')
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
plt.plot(y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot y value without given x values')
plt.axis([0, 7, 0, 10])
plt.savefig('axis.png')
X = np.arange(5)
Y = 3.14 + 2.71 * np.random.rand(5)
plt.subplots(2)
plt.subplot(211)
plt.bar(X, Y, align='center', alpha=0.4, color='y')
plt.xlabel('x')
plt.ylabel('y')
plt.title('bar plot in vertical')
plt.subplot(212)
plt.barh(X, Y, align='center', alpha=0.4, color='c')
plt.xlabel('x')
plt.ylabel('y')
plt.title('bar plot in horizontal')
plt.savefig('bar.png')
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
plt.axis([0, 6, 0, 10])
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Data Visualization using Pyplot from Matplotlib')
plt.savefig('better.png')
x = np.linspace(-1, 1, 255)
y = np.linspace(-2, 2, 300)
z = np.sin(y[:, np.newaxis] * np.cos(x))
plt.contour(x, y, z, 255, linewidth=2)
plt.savefig('contour.png')
/usr/local/lib/python3.6/dist-packages/matplotlib/contour.py:1000: UserWarning: The following kwargs were not used by contour: 'linewidth' s)
data = {'Median_Age': [24.2, 26.4, 28.5, 30.3],
'Density': [244, 256, 268, 279]}
index_label = ['2000', '2005', '2010', '2014'];
df1 = pd.DataFrame(data, index=index_label)
df1.plot(kind='bar', subplots=True, sharex=True)
plt.tight_layout()
plt.savefig('df.png')
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Data Visualization using Pyplot from Matplotlib')
plt.savefig('intro.png')
x = np.linspace(0, 1, 20);
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
plt.plot(x, y1, 'c', label='y=sin(x)')
plt.plot(x, y2, 'y', label='y=cos(x)')
plt.plot(x, y3, 'r', label='y=tan(x)')
plt.legend(loc='upper left')
plt.savefig('legends.png')
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
plt.plot(x*2, 'g^', x*3, 'rs', x**x, 'y-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot y value without given x values')
plt.axis([0, 6, 0, 30])
plt.savefig('line.png')
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
line, = plt.plot(y, color='red', linewidth=2.0)
line.set_linestyle('--')
plt.setp(line, marker='o')
plt.savefig('linestyle.png')
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2.4, 0.4, 20)
y = x * x + 2 * x + 1
plt.plot(x, y, 'c', linewidth=2.0)
plt.text(-1.5, 1.8, 'y=x^2 + 2*x + 1',
fontsize=14, style='italic')
plt.annotate('minima point', xy=(-1, 0),
xytext=(-1, 0.3), horizontalalignment='center',
verticalalignment='top',
arrowprops=dict(arrowstyle='->',
connectionstyle='arc3'))
plt.savefig('annotate.png')
x = np.linspace(0, 1, 20);
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
p1 = plt.plot(x, y1, 'c', label='y=sin(x)')
p2 = plt.plot(x, y2, 'y', label='y=cos(x)')
p3 = plt.plot(x, y3, 'r', label='y=tan(x)')
lsin = plt.legend(handles=p1, loc='lower right')
lcos = plt.legend(handles=p2, loc='upper left')
ltan = plt.legend(handles=p3, loc='upper right')
fig = plt.gcf()
fig.gca().add_artist(lsin)
fig.gca().add_artist(lcos)
plt.tight_layout()
plt.savefig('morelegends.png')
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
plt.plot(y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot y value without given x values')
plt.savefig('nox.png')
s = pd.Series(np.random.normal(10, 8, 20))
s.plot(style='ko-', alpha=0.4, label='Series plotting')
plt.legend()
plt.savefig('pandasplot.png')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
s = pd.Series(np.random.normal(10, 8, 20))
s.plot(style='ko-', alpha=0.4, label='Series plotting')
plt.legend()
plt.savefig('pandasplot.png')
s = pd.Series(np.random.normal(10, 8, 20))
s.plot(style='ko-', alpha=0.4)
plt.legend(['Series plotting'])
plt.savefig('series.png')
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
plt.figure('a')
plt.subplot(221)
plt.plot(y + y, 'r--')
plt.subplot(222)
plt.plot(y * 3, 'ko')
plt.subplot(223)
plt.plot(y * y, 'b^')
plt.subplot(224)
# alter things after the fact
plt.figure('a')
plt.subplot(222)
plt.title('Visualization of y * 3')
plt.savefig('subplot.png')
/usr/local/lib/python3.6/dist-packages/matplotlib/figure.py:98: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. "Adding an axes using the same arguments as a previous axes "
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
# another figure
plt.figure('b')
ax1 = plt.axes([0.05, 0.1, 0.4, 0.32])
ax2 = plt.axes([0.52, 0.1, 0.4, 0.32])
ax3 = plt.axes([0.05, 0.53, 0.87, 0.44])
plt.savefig('subs.png')
s = pd.Series(np.random.normal(10, 8, 20))
s.plot(style='ko-', alpha=0.4, label='Series plotting')
plt.legend()
plt.savefig('pandasplot.png')
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(12,9))
ax = fig.gca(projection='3d')
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.6, aspect=6)
plt.show()
# create n values of x from 0 to 2*pi
x = np.linspace(0, 8*np.pi, 100)
y = np.sin(x/2)
#interpolate new y-values
yinterp = np.interp(x, x, y)
#plot x,y values using circle marker (line style)
plt.plot(x, y, 'o')
#plot interpolated curve using dash x marker
plt.plot(x, yinterp, '-x')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
# Set up the figure, axis, and the plot element to be animated
fig = plt.figure()
ax = plt.axes(xlim=(0, 3.2), ylim=(-2.14, 2.14))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
xval = 2 * np.pi * (x - 0.01 * i)
y = np.cos(xval) # Here we are trying to animate cos function
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,\
frames=200, interval=20, blit=True)
anim.save('basic_animation.mp4', fps=30)
plt.show()
from numpy.random import standard_normal
from numpy import zeros, sqrt
import matplotlib.pyplot as plt
S_init = 20.222
T =1
tstep =0.0002
sigma = 0.4
mu = 1
NumSimulation=6
colors = [ (214,27,31), (148,103,189), (229,109,0), (41,127,214),
(227,119,194),(44,160,44),(227,119,194), (72,17,121), (196,156,148)]
# Scale the RGB values to the [0, 1] range.
for i in range(len(colors)):
r, g, b = colors[i]
colors[i] = (r / 255., g / 255., b / 255.)
plt.figure(figsize=(12,12))
Steps=round(T/tstep); #Steps in years
S = zeros([NumSimulation, Steps], dtype=float)
x = range(0, int(Steps), 1)
for j in range(0, NumSimulation, 1):
S[j,0]= S_init
for i in x[:-1]:
S[j,i+1]=S[j,i]+S[j,i]*(mu-0.5*pow(sigma,2))*tstep+ \
sigma*S[j,i]*sqrt(tstep)*standard_normal()
plt.plot(x, S[j], linewidth=2., color=colors[j])
plt.title('%d Simulation using %d Steps, \n$\sigma$=%.6f $\mu$=%.6f $S_0$=%.6f ' % (int(NumSimulation), int(Steps), sigma, mu, S_init),
fontsize=18)
plt.xlabel('steps', fontsize=16)
plt.grid(True)
plt.ylabel('stock price', fontsize=16)
plt.ylim(0,90)
plt.show()
import matplotlib.pyplot as plt
from numpy import concatenate, zeros, ones, hamming, convolve
digital = concatenate ( (zeros(20), ones(25), zeros(20)))
norm_hamming = hamming(80)/sum(hamming(80))
res = convolve(digital, norm_hamming)
plt.figure(figsize=(10,10))
plt.ylim(0, 0.6)
plt.plot(res, color='r', linewidth=2)
plt.hold(True)
plt.plot(data, color='b', linewidth=3)
plt.hold(True)
plt.plot(norm_hamming, color='g', linewidth=4)
plt.show()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-40-757aca728f98> in <module>() 8 plt.ylim(0, 0.6) 9 plt.plot(res, color='r', linewidth=2) ---> 10 plt.hold(True) 11 plt.plot(data, color='b', linewidth=3) 12 plt.hold(True) AttributeError: module 'matplotlib.pyplot' has no attribute 'hold'