elena1234

Matplotlib exercises in Python

Apr 26th, 2022 (edited)
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4.  
  5. # Task 1: Import what you need from Matplotlib to plot out graphs
  6. m = np.linspace(0,10,11)
  7. c = 299792458
  8. E = m * (c*c)
  9.  
  10. fig,axes = plt.subplots()
  11. axes.plot(m, E, color = "red", linewidth = 4)
  12. axes.set_xlabel('Mass in Grams')
  13. axes.set_ylabel('Energy in Joules')
  14. axes.set_title('E=mc^2')
  15. axes.set_xlim(xmin = 0, xmax = 10)
  16.  
  17. # How to plot logarithmic scale on y axis
  18. axes.set_yscale('log')
  19.  
  20. # How to set a grid on y axis
  21. axes.yaxis.grid(True, which='minor')
  22.  
  23.  
  24. # Task 2: Figure out how to plot both curves on the same Figure
  25. labels = ['1 Mo','3 Mo','6 Mo','1 Yr','2 Yr','3 Yr','5 Yr','7 Yr','10 Yr','20 Yr','30 Yr']
  26. july16_2007 =[4.75,4.98,5.08,5.01,4.89,4.89,4.95,4.99,5.05,5.21,5.14]
  27. july16_2020 = [0.12,0.11,0.13,0.14,0.16,0.17,0.28,0.46,0.62,1.09,1.31]
  28.  
  29. fig = plt.figure(figsize = (5,4),dpi=400)
  30. axes1 = fig.add_axes([0,0,1,1])
  31.  
  32. axes1.plot(labels, july16_2007, label = 'july16_2007') # for first curve
  33. axes1.set_ylim(ymin = 0, ymax = 5.5)
  34.  
  35. axes1.plot(labels, july16_2020,  label = 'july16_2020') # for second curve
  36. axes1.legend(loc = [1.05, 0.5]) # the legend is set out of the plot
  37.  
  38.  
  39. # Task 3: Create two different plots
  40. fig1,axes2 = plt.subplots(nrows=2, ncols = 1, dpi = 200, figsize = (10,6))
  41. axes2[0].plot(labels,july16_2007)
  42. axes2[0].set_xlabel('july16_2007', loc = 'center')
  43. axes2[1].plot(labels,july16_2020)
  44. axes2[1].set_xlabel('july16_2020', loc = 'center')
  45.  
  46. fig1.tight_layout()
  47.  
  48.  
  49. # Task 4: How to add two y axis and changed their color
  50. x = labels
  51. y1 = july16_2007
  52. y2 = july16_2020
  53.  
  54. fig, ax1 = plt.subplots()
  55. ax2 = ax1.twinx()
  56.  
  57. ax1.plot(x, y1, color = 'blue')
  58. ax2.plot(x, y2, color = 'red')
  59.  
  60. ax1.set_ylabel('2007', color='blue')
  61. ax2.set_ylabel('2020', color='red')
  62.  
  63. ax2.spines['left'].set_color('blue')
  64. ax2.spines['right'].set_color('red')
  65.  
Add Comment
Please, Sign In to add comment