<jupyter_start><jupyter_text>MatplotlibTutorials adapted from:* https://github.com/matplotlib/AnatomyOfMatplotlib* https://github.com/matplotlib/cheatsheetsOther useful sources:* https://github.com/jbmouret/matplotlib_for_papers  IntroductionMatplotlib is a library for producing publication-quality figures. mpl (for short) was designed from the beginning to serve two purposes:  1. allow for interactive, cross-platform control of figures and plots 2. make it easy to produce static raster or vector graphics files without the need for any GUIs.  Furthermore, mpl -- much like Python itself -- gives the developer complete control over the appearance of their plots, while still being very usable through a powerful defaults system.  Online DocumentationThe [matplotlib.org](http://matplotlib.org) project website is the primary online resource for the library's documentation. It contains the [example galleries](https://matplotlib.org/gallery/index.html), [FAQs](http://matplotlib.org/faq/index.html), [API documentation](http://matplotlib.org/api/index.html), and [tutorials](https://matplotlib.org/tutorials/index.html). GalleryMany users of Matplotlib are often faced with the question, "I want to make a figure that has X with Y in the same figure, but it needs to look like Z". Good luck getting an answer from a web search with that query! This is why the [gallery](https://matplotlib.org/gallery/index.html) is so useful, because it showcases the variety of ways one can make figures. Browse through the gallery, click on any figure that has pieces of what you want to see and the code that generated it. Soon enough, you will be like a chef, mixing and matching components to produce your masterpiece!As always, if you have a new and interesting plot that demonstrates a feature of Matplotlib, feel free to submit a concise, well-commented version of the code for inclusion in the gallery. Mailing Lists, StackOverflow, and gitterWhen you are just simply stuck, and cannot figure out how to get something to work, or just need some hints on how to get started, you will find much of the community at the matplotlib-users [mailing list](https://mail.python.org/mailman/listinfo/matplotlib-users). This mailing list is an excellent resource of information with many friendly members who just love to help out newcomers. We love plots, so an image showing what is wrong often gets the quickest responses.Another community resource is [StackOverflow](http://stackoverflow.com/questions/tagged/matplotlib), so if you need to build up karma points, submit your questions here, and help others out too! We are also on [Gitter](https://gitter.im/matplotlib/matplotlib). If you are working interactively at an (I)python prompt, the GUI framework is not critical (mostly aesthetic) however when working in Jupyter we need to pick a backend that integrates with Jupyter (javascript) framework.To select the backend use ``matplotlib.use("backend_name")``, in this case we want ``'nbagg'``  Getting StartedIn this tutorial, we'll use the following import statements. These abbreviations are semi-standardized, and most tutorials, other scientific python code that you'll find elsewhere will use them as well.<jupyter_code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>Prepare Data<jupyter_code>X = np.linspace (0, 4*np.pi, 100)
Y1 = np.sin(X)
Y2 = np.cos(X)<jupyter_output><empty_output><jupyter_text>Draw Plot<jupyter_code># draw sine plot
fig, ax = plt.subplots() #no argument in subplots mean just one plot in figure
ax.plot(X,Y1) #plot X, Y1 in 'ax' axis (subplot)
plt.show()
# draw cosine plot
fig, ax = plt.subplots()
ax.plot(X,Y2)
plt.show()<jupyter_output><empty_output><jupyter_text>As you can see the function ``subplots()`` above generates two outputs: ``figure`` (fig) and ``axes`` (ax). Figure is the overall window/page that can contain multiple ``Axes``.   Axes``Axes`` is effectively the area that we plot data on and any ticks/labels/etc associated with it.  Usually we'll set up an Axes with a call to ``subplot`` (which places Axes on a regular grid), so in most cases, ``Axes`` and ``Subplot`` are synonymous.<jupyter_code># plot two graphs on one axis (subplots)
fig, ax = plt.subplots()
ax.plot(X,Y1)
ax.plot(X,Y2)
plt.show()
# plot two graphs on two axes (subplots)
fig, (ax1, ax2) = plt.subplots(2,1) #2 by 1 format
ax1.plot(X,Y1, color='C1')
ax2.plot(X,Y2, color='C0')
plt.show()
# plot two graphs on two axes (subplots) 
fig, (ax1, ax2) = plt.subplots(1,2) #1 by 2 format
ax1.plot(X,Y1, color='C1')
ax2.plot(X,Y2, color='C0')
plt.show()<jupyter_output><empty_output><jupyter_text>or we can also create ``figure`` first then add ``axis``<jupyter_code>fig = plt.figure()
ax = fig.add_subplot(111) # We'll explain the "111" later. Basically, 1 row and 1 column.
ax.plot(X,Y1)
plt.show()
fig = plt.figure()
ax1 = fig.add_subplot(211) # We'll explain the "111" later. Basically, it means  "2x1 grid, first subplot"
ax1.plot(X,Y1)

ax2 = fig.add_subplot(212) # "2x1 grid, second subplot"
ax2.plot(X,Y2)

plt.show()<jupyter_output><empty_output><jupyter_text>When we want to change something about each axis, we use ``set_``. and control a particular option. To demonstrate this (and as an example of IPython's tab-completion), try typing `ax.set_` in a code cell, then hit the `` key.  You'll see a long list of `Axes` methods that start with `set`.<jupyter_code>fig, ax = plt.subplots()
ax.plot(X,Y1)

ax.set_title('A Different Example Axes Title')

ax.set_xlim([0, 10])
ax.set_ylim([0, 1])

ax.set_ylabel('Y-Axis (changed)')
ax.set_xlabel('X-Axis (changed)')

ax.set_xticks(range(0, 11, 2))
ax.set_xticklabels(['zero', 'two', 'four', 'six', 'eight', 'ten'])

plt.show()
## or you can do this way
fig, ax = plt.subplots()
ax.plot(X,Y1)

ax.set(xlim= [0, 10], ylim=[0, 1], title ='A Different Example Axes Title', 
       ylabel='Y-Axis (changed)',xlabel= 'X-Axis (changed)',
      xticks =range(0, 11, 2), xticklabels=['zero', 'two', 'four', 'six', 'eight', 'ten'] )
plt.show()
# you can also use ticklocators API for xticks and yticks setting

from matplotlib import ticker
fig, ax = plt.subplots()
ax.plot(X,Y1)

ax.set_title('A Different Example Axes Title')

ax.set_xlim([0, 10])
ax.set_ylim([0, 1])

ax.set_ylabel('Y-Axis (changed)')
ax.set_xlabel('X-Axis (changed)')

ax.xaxis.set_major_locator(ticker.MultipleLocator(2.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.5))

plt.show()<jupyter_output><empty_output><jupyter_text>modify graphs You can modify colors, markers, styles of graphs by passing arguments in ``.plot``<jupyter_code># this is default plot
fig, ax = plt.subplots() 
ax.plot(X,Y1)
plt.show()
# change linecolor
fig, ax = plt.subplots() 
ax.plot(X,Y1, color='black')
plt.show()
# change line style
fig, ax = plt.subplots() 
ax.plot(X,Y1, linestyle='--')
plt.show()
# change linewidth
fig, ax = plt.subplots() 
ax.plot(X,Y1, linewidth=5)
plt.show()
# change marker
fig, ax = plt.subplots() 
ax.plot(X,Y1, marker='o')
plt.show()<jupyter_output><empty_output><jupyter_text>Matplotlib offers several kinds of plots!Also see [galleries](https://matplotlib.org/gallery/index.html)<jupyter_code># scatter plot
X = np.random.uniform(0,1,100)
Y = np.random.uniform(0,1,100)
fig,ax = plt.subplots()

ax.scatter(X,Y)
plt.show()
# bar plot
X = np.arange(10)
Y = np.random.uniform(0,10,10)
fig,ax = plt.subplots()
ax.bar(X,Y)
plt.show()
#histogram
Z = np.random.normal(0,1,100)
fig,ax = plt.subplots()
ax.hist(Z)
plt.show()<jupyter_output><empty_output><jupyter_text>Miscellenous<jupyter_code>## text and ornaments
X = np.linspace(0, 10, 100)
Y = np.cos(X)
fig, ax = plt.subplots()

ax.plot(X,Y)

ax.fill_between(x=[0,5],y1=-1, y2=1, color='black', alpha = 0.2)
ax.text(0, -1, "Period $\phi$")

plt.show()<jupyter_output><empty_output><jupyter_text>Exercise 1: Reproduce the figure below using line plot<jupyter_code># Our data...
x = np.linspace(0, 10, 100)
y1, y2, y3 = np.cos(x), np.cos(x + 1), np.cos(x + 2)
names = ['Signal 1', 'Signal 2', 'Signal 3']
# your implementation<jupyter_output><empty_output><jupyter_text>Exercise 2: Reproduce the figure below using barplot<jupyter_code># Data for barplots
means = [9, 8, 6] 
ses = [1.5, 0.7, 1.0]

# Your implementation here:<jupyter_output><empty_output><jupyter_text>Exercise 3: Reproduce the figure below using subplots (advanced, optional)<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [5, 4]
plt.rcParams['figure.dpi'] = 150

np.random.seed(1)

# Generate data...
y_raw = np.random.randn(1000).cumsum() + 15
x_raw = np.linspace(0, 24, y_raw.size)

# Get averages of every 100 samples...
x_pos = x_raw.reshape(-1, 100).min(axis=1)
y_avg = y_raw.reshape(-1, 100).mean(axis=1)
y_err = y_raw.reshape(-1, 100).ptp(axis=1)

bar_width = x_pos[1] - x_pos[0]

# Make a made up future prediction with a fake confidence
x_pred = np.linspace(0, 30)
y_max_pred = y_avg[0] + y_err[0] + 2.3 * x_pred
y_min_pred = y_avg[0] - y_err[0] + 1.2 * x_pred

# Just so you don't have to guess at the colors...
barcolor, linecolor, fillcolor = 'wheat', 'salmon', 'lightblue'


# Now you're on your own!<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13004338394793927, 'fraction_numerical': 0.02299349240780911, 'mean_word_length': 5.285616905248807, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 49, 'https://': 9, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '263665', 'license': 'MIT', 'n_tokens_mistral': 3394, 'n_tokens_neox': 3212, 'n_words': 1047, 'path': 'tutorials/Ch8. Matplotlib.ipynb', 'repo_name': 'ahnchive/python-workshop', 'size': '9220'}