Either interactively, such as from within an Ipython session, or from within a script, how can you determine which backend is being used by matplotlib?
I have a pandas data frame and would like to plot values from one column versus the values from another column. Fortunately, there is plot method associated with the data-frames that seems to do what I need:
df.plot(x='col_name_1', y='col_name_2')
Unfortunately, it looks like among the plot styles (listed here after the kind parameter) there are not points. I can use lines or bars or even density but not points. Is there a work around that can help to solve this problem.
import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show()# Depending on whether you use IPython or interactive mode, etc.
For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly:
import matplotlib.pyplot as plt
plt.scatter(df['col_name_1'], df['col_name_2'])
plt.show() # Depending on whether you use IPython or interactive mode, etc.
and remember that you can access a NumPy array of the column’s values with df.col_name_1.values for example.
Pandas uses matplotlib as a library for basic plots. The easiest way in your case will using the following:
import pandas as pd
import numpy as np
#creating sample data
sample_data={'col_name_1':np.random.rand(20),
'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
df.plot(x='col_name_1', y='col_name_2', style='o')
However, I would recommend to use seaborn as an alternative solution if you want have more customized plots while not going into the basic level of matplotlib. In this case you the solution will be following:
import pandas as pd
import seaborn as sns
import numpy as np
#creating sample data
sample_data={'col_name_1':np.random.rand(20),
'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df)
The resulting figure is very small at the center of the grey window, while most of the space is unoccupied. How can I set the parameters to make the figure larger? I tried figsize=(xx,xx) and it’s not what I want. Thanks!
If you don’t give an aspect argument to imshow, it will use the value for image.aspect in your matplotlibrc. The default for this value in a new matplotlibrc is equal.
So imshow will plot your array with equal aspect ratio.
If you don’t need an equal aspect you can set aspect to auto
from matplotlib import pyplot as plt
import random
import numpy as np
random = np.random.random ([8,90])
plt.figure(figsize =(20,2))
plt.imshow(random, interpolation='nearest')
as requested by @baxxx, here is an update because random.rand is deprecated meanwhile.
This works with matplotlip 3.2.1:
from matplotlib import pyplot as plt
import random
import numpy as np
random = np.random.random ([8,90])
plt.figure(figsize = (20,2))
plt.imshow(random, interpolation='nearest')
This plots:
To change the random number, you can experiment with np.random.normal(0,1,(8,90)) (here mean = 0, standard deviation = 1).
import numpy as np
import matplotlib.pyplot as plt
t= np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)
fig=plt.figure()
ax1 = plt.subplot(211)
plt.plot(t,x)
ax2 = plt.subplot(212)
plt.plot(t,y)
# some code to share both x axis
plt.show()
I’m trying to share two subplots axis, but I need to share x axis after the figure was created.
So, for instance, I create this figure:
import numpy as np
import matplotlib.pyplot as plt
t= np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)
fig=plt.figure()
ax1 = plt.subplot(211)
plt.plot(t,x)
ax2 = plt.subplot(212)
plt.plot(t,y)
# some code to share both x axis
plt.show()
Instead of the comment I would insert some code to share both x axis.
I didn’t find any clue how i can do that. There are some attributes
_shared_x_axes and _shared_x_axes when i check to figure axis (fig.get_axes()) but I don’t know how to link them.
Sharing the axes after they have been created should therefore not be necessary.
However if for any reason, you need to share axes after they have been created (actually, using a different library which creates some subplots, like here, or sharing an inset axes might be a reason), there would still be a solution:
Using
ax1.get_shared_x_axes().join(ax1, ax2)
creates a link between the two axes, ax1 and ax2. In contrast to the sharing at creation time, you will have to set the xticklabels off manually for one of the axes (in case that is wanted).
A complete example:
import numpy as np
import matplotlib.pyplot as plt
t= np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*10*t)
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
ax1.plot(t,x)
ax2.plot(t,y)
ax1.get_shared_x_axes().join(ax1, ax2)
ax1.set_xticklabels([])
# ax2.autoscale() ## call autoscale if needed
plt.show()
I went through the examples in the matplotlib documentation, but it wasn’t clear to me how I can make a plot that fills the area between two specific vertical lines.
For example, say I want to create a plot between x=0.2 and x=4 (for the full y range of the plot). Should I use fill_between, fill or fill_betweenx?
It sounds like you want axvspan, rather than one of the fill between functions. The differences is that axvspan (and axhspan) will fill up the entire y (or x) extent of the plot regardless of how you zoom.
For example, let’s use axvspan to highlight the x-region between 8 and 14:
You could use fill_betweenx to do this, but the extents (both x and y) of the rectangle would be in data coordinates. With axvspan, the y-extents of the rectangle default to 0 and 1 and are in axes coordinates (in other words, percentages of the height of the plot).
To illustrate this, let’s make the rectangle extend from 10% to 90% of the height (instead of taking up the full extent). Try zooming or panning, and notice that the y-extents say fixed in display space, while the x-extents move with the zoom/pan:
Python indexing starts at 0 (rather than 1), so your assignment “r[1,:] = r0” defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.
To prevent division by zero you could pre-initialize the output ‘out’ where the div0 error happens, eg np.where does not cut it since the complete line is evaluated regardless of condition.
/usr/lib/pymodules/python2.7/matplotlib/legend.py:610:UserWarning:Legend does not support [<matplotlib.lines.Line2D object at 0x3a30810>]Use proxy artist instead.
http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist
warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n"%(str(orig_handle),))/usr/lib/pymodules/python2.7/matplotlib/legend.py:610:UserWarning:Legend does not support [<matplotlib.lines.Line2D object at 0x3a30990>]Use proxy artist instead.
http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist
warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n"%(str(orig_handle),))
这种情况甚至发生在像这样的琐碎脚本中:
import matplotlib.pyplot as plt
a =[1,2,3]
b =[4,5,6]
c =[7,8,9]
plot1 = plt.plot(a,b)
plot2 = plt.plot(a,c)
plt.legend([plot1,plot2],["plot 1","plot 2"])
plt.show()
Ever since upgrading matplotlib I get the following error whenever trying to create a legend:
/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x3a30810>]
Use proxy artist instead.
http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist
warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),))
/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [<matplotlib.lines.Line2D object at 0x3a30990>]
Use proxy artist instead.
http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist
warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),))
This even occurs with a trivial script like this:
import matplotlib.pyplot as plt
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
plot1 = plt.plot(a,b)
plot2 = plt.plot(a,c)
plt.legend([plot1,plot2],["plot 1", "plot 2"])
plt.show()
I’ve found the link that the error points me towards pretty useless in diagnosing the source of the error.
The reason you need the commas is because plt.plot() returns a tuple of line objects, no matter how many are actually created from the command. Without the comma, “plot1” and “plot2” are tuples instead of line objects, making the later call to plt.legend() fail.
The comma implicitly unpacks the results so that instead of a tuple, “plot1” and “plot2” automatically become the first objects within the tuple, i.e. the line objects you actually want.
I am trying to make a discrete colorbar for a scatterplot in matplotlib
I have my x, y data and for each point an integer tag value which I want to be represented with a unique colour, e.g.
plt.scatter(x, y, c=tag)
typically tag will be an integer ranging from 0-20, but the exact range may change
so far I have just used the default settings, e.g.
plt.colorbar()
which gives a continuous range of colours. Ideally i would like a set of n discrete colours (n=20 in this example). Even better would be to get a tag value of 0 to produce a gray colour and 1-20 be colourful.
I have found some ‘cookbook’ scripts but they are very complicated and I cannot think they are the right way to solve a seemingly simple problem
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
fig, ax = plt.subplots(1,1, figsize=(6,6))# setup the plot
x = np.random.rand(20)# define the data
y = np.random.rand(20)# define the data
tag = np.random.randint(0,20,20)
tag[10:12]=0# make sure there are some 0 values to show up as grey
cmap = plt.cm.jet # define the colormap# extract all colors from the .jet map
cmaplist =[cmap(i)for i in range(cmap.N)]# force the first color entry to be grey
cmaplist[0]=(.5,.5,.5,1.0)# create the new map
cmap = mpl.colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplist, cmap.N)# define the bins and normalize
bounds = np.linspace(0,20,21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)# make the scatter
scat = ax.scatter(x, y, c=tag, s=np.random.randint(100,500,20),
cmap=cmap, norm=norm)# create a second axes for the colorbar
ax2 = fig.add_axes([0.95,0.1,0.03,0.8])
cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')
ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)
You can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey.
For images i often use the cmap.set_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get this to work with the scatter or the custom cmap.
As an alternative you can make your own cmap from scratch, or read-out an existing one and override just some specific entries.
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
fig, ax = plt.subplots(1, 1, figsize=(6, 6)) # setup the plot
x = np.random.rand(20) # define the data
y = np.random.rand(20) # define the data
tag = np.random.randint(0, 20, 20)
tag[10:12] = 0 # make sure there are some 0 values to show up as grey
cmap = plt.cm.jet # define the colormap
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
cmaplist[0] = (.5, .5, .5, 1.0)
# create the new map
cmap = mpl.colors.LinearSegmentedColormap.from_list(
'Custom cmap', cmaplist, cmap.N)
# define the bins and normalize
bounds = np.linspace(0, 20, 21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
# make the scatter
scat = ax.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20),
cmap=cmap, norm=norm)
# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')
ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)
I personally think that with 20 different colors its a bit hard to read the specific value, but thats up to you of course.
#!/usr/bin/env python"""
Use a pcolor or imshow with a custom colormap to make a contour plot.
Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""from pylab import*
delta =0.01
x = arange(-3.0,3.0, delta)
y = arange(-3.0,3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y,1.0,1.0,0.0,0.0)
Z2 = bivariate_normal(X, Y,1.5,0.5,1,1)
Z = Z2 - Z1 # difference of Gaussians
cmap = cm.get_cmap('PiYG',11)# 11 discrete colors
im = imshow(Z, cmap=cmap, interpolation='bilinear',
vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()
show()
#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.
Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""
from pylab import *
delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians
cmap = cm.get_cmap('PiYG', 11) # 11 discrete colors
im = imshow(Z, cmap=cmap, interpolation='bilinear',
vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()
show()
import matplotlib.pyplot as plt
import numpy as np
def discrete_matshow(data):#get discrete colormap
cmap = plt.get_cmap('RdBu', np.max(data)-np.min(data)+1)# set limits .5 outside true range
mat = plt.matshow(data,cmap=cmap,vmin = np.min(data)-.5, vmax = np.max(data)+.5)#tell the colorbar to tick at integers
cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))#generate data
a=np.random.randint(1,9, size=(10,10))
discrete_matshow(a)
The above answers are good, except they don’t have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:
import matplotlib.pyplot as plt
import numpy as np
def discrete_matshow(data):
#get discrete colormap
cmap = plt.get_cmap('RdBu', np.max(data)-np.min(data)+1)
# set limits .5 outside true range
mat = plt.matshow(data,cmap=cmap,vmin = np.min(data)-.5, vmax = np.max(data)+.5)
#tell the colorbar to tick at integers
cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))
#generate data
a=np.random.randint(1, 9, size=(10, 10))
discrete_matshow(a)
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
x, y, z = np.random.random((3,30))
z = z *20+0.1# Set some values in z to 0...
z[:5]=0
cmap = plt.get_cmap('jet',20)
cmap.set_under('gray')
fig, ax = plt.subplots()
cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=0.1, vmax=z.max())
fig.colorbar(cax, extend='min')
plt.show()
To set a values above or below the range of the colormap, you’ll want to use the set_over and set_under methods of the colormap. If you want to flag a particular value, mask it (i.e. create a masked array), and use the set_bad method. (Have a look at the documentation for the base colormap class: http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap )
It sounds like you want something like this:
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
x, y, z = np.random.random((3, 30))
z = z * 20 + 0.1
# Set some values in z to 0...
z[:5] = 0
cmap = plt.get_cmap('jet', 20)
cmap.set_under('gray')
fig, ax = plt.subplots()
cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=0.1, vmax=z.max())
fig.colorbar(cax, extend='min')
plt.show()
import matplotlib
from matplotlib.colors importListedColormap# Let's design a dummy land use field
A = np.reshape([7,2,13,7,2,2],(2,3))
vals = np.unique(A)# Let's also design our color mapping: 1s should be plotted in blue, 2s in red, etc...
col_dict={1:"blue",2:"red",13:"orange",7:"green"}# We create a colormar from our list of colors
cm =ListedColormap([col_dict[x]for x in col_dict.keys()])# Let's also define the description of each category : 1 (blue) is Sea; 2 (red) is burnt, etc... Order should be respected here ! Or using another dict maybe could help.
labels = np.array(["Sea","City","Sand","Forest"])
len_lab = len(labels)# prepare normalizer## Prepare bins for the normalizer
norm_bins = np.sort([*col_dict.keys()])+0.5
norm_bins = np.insert(norm_bins,0, np.min(norm_bins)-1.0)print(norm_bins)## Make normalizer and formatter
norm = matplotlib.colors.BoundaryNorm(norm_bins, len_lab, clip=True)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: labels[norm(x)])# Plot our figure
fig,ax = plt.subplots()
im = ax.imshow(A, cmap=cm, norm=norm)
diff = norm_bins[1:]- norm_bins[:-1]
tickz = norm_bins[:-1]+ diff /2
cb = fig.colorbar(im, format=fmt, ticks=tickz)
fig.savefig("example_landuse.png")
plt.show()
This topic is well covered already but I wanted to add something more specific : I wanted to be sure that a certain value would be mapped to that color (not to any color).
It is not complicated but as it took me some time, it might help others not lossing as much time as I did :)
import matplotlib
from matplotlib.colors import ListedColormap
# Let's design a dummy land use field
A = np.reshape([7,2,13,7,2,2], (2,3))
vals = np.unique(A)
# Let's also design our color mapping: 1s should be plotted in blue, 2s in red, etc...
col_dict={1:"blue",
2:"red",
13:"orange",
7:"green"}
# We create a colormar from our list of colors
cm = ListedColormap([col_dict[x] for x in col_dict.keys()])
# Let's also define the description of each category : 1 (blue) is Sea; 2 (red) is burnt, etc... Order should be respected here ! Or using another dict maybe could help.
labels = np.array(["Sea","City","Sand","Forest"])
len_lab = len(labels)
# prepare normalizer
## Prepare bins for the normalizer
norm_bins = np.sort([*col_dict.keys()]) + 0.5
norm_bins = np.insert(norm_bins, 0, np.min(norm_bins) - 1.0)
print(norm_bins)
## Make normalizer and formatter
norm = matplotlib.colors.BoundaryNorm(norm_bins, len_lab, clip=True)
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: labels[norm(x)])
# Plot our figure
fig,ax = plt.subplots()
im = ax.imshow(A, cmap=cm, norm=norm)
diff = norm_bins[1:] - norm_bins[:-1]
tickz = norm_bins[:-1] + diff / 2
cb = fig.colorbar(im, format=fmt, ticks=tickz)
fig.savefig("example_landuse.png")
plt.show()
import matplotlib, numpy as np, matplotlib.pyplot as plt
n =5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x %11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)
I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm as well as specifying norm as an argument to scatter and colorbar. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list.
Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1, e.g., has 9 easily distinguishable colors, and tab20 could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.
import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)
which produces the image below. The n in the call to Set1 specifies
the first n colors of that colormap, and the last n in the call to from_list
specifies to construct a map with n colors (the default being 256). In order to set cm as the default colormap with plt.set_cmap, I found it to be necessary to give it a name and register it, viz:
cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)
I think you’d want to look at colors.ListedColormap to generate your colormap, or if you just need a static colormap I’ve been working on an app that might help.
I have a list of pairs (a, b) that I would like to plot with matplotlib in python as actual x-y coordinates. Currently, it is making two plots, where the index of the list gives the x-coordinate, and the first plot’s y values are the as in the pairs and the second plot’s y values are the bs in the pairs.
To clarify, my data looks like this: li = [(a,b), (c,d), ... , (t, u)]
I want to do a one-liner that just calls plt.plot() incorrect.
If I didn’t require a one-liner I could trivially do:
xs = [x[0] for x in li]
ys = [x[1] for x in li]
plt.plot(xs, ys)
How can I get matplotlib to plot these pairs as x-y coordinates?
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end.
I hope that this is what you wanted.
How can I plot the following 3 functions (i.e. sin, cos and the addition), on the domain t, in the same figure?
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
回答 0
要在同一图形上绘制多个图形,您必须执行以下操作:
from numpy import*import math
import matplotlib.pyplot as plt
t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a,'r')# plotting t, a separately
plt.plot(t, b,'b')# plotting t, b separately
plt.plot(t, c,'g')# plotting t, c separately
plt.show()
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
回答 1
也许是更Python化的方式。
from numpy import*import math
import matplotlib.pyplot as plt
t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, t, b, t, c)
plt.show()
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, t, b, t, c)
plt.show()