Can you plot objects in python?
I want to plot 'Date Read' with respect to 'Original Publication Year' using Pandas in Python. Show
Pandas Version = '0.16.2'
When I try to plot the same I get error " KeyError: 'Date Read' "
I'm I doing anything wrong here ? Do I need to convert the 'Date Read' to some other format here ? [Edit1] I get the same error even after converting the 'Date Read' and 'Original Publication Year' to datetime. Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Plotting With Matplotlib A picture is worth a thousand words, and with Python’s matplotlib library, it fortunately takes far less than a thousand words of code to create a production-quality graphic. However, matplotlib is also a massive library, and getting a plot to look just right is often achieved through trial and error. Using one-liners to generate basic plots in matplotlib is fairly simple, but skillfully commanding the remaining 98% of the library can be daunting. This article is a beginner-to-intermediate-level walkthrough on matplotlib that mixes theory with examples. While learning by example can be tremendously insightful, it helps to have even just a surface-level understanding of the library’s inner workings and layout as well. Here’s what we’ll cover:
This article assumes the user knows a tiny bit of NumPy. We’ll mainly use the
If you don’t already have matplotlib installed, see here for a walkthrough before proceeding. Why Can Matplotlib Be Confusing?Learning matplotlib can be a frustrating process at times. The problem is not that matplotlib’s documentation is lacking: the documentation is actually extensive. But the following issues can cause some challenges:
So, before we get to any glitzy examples, it’s useful to grasp the core concepts of matplotlib’s design. Pylab: What Is It, and Should I Use It?Let’s start with a bit of history: John D. Hunter, a neurobiologist, began developing matplotlib around 2003, originally inspired to emulate commands from Mathworks’ MATLAB software. John passed away tragically young at age 44, in 2012, and matplotlib is now a full-fledged community effort, developed and maintained by a host of others. (John gave a talk about the evolution of matplotlib at the 2012 SciPy conference, which is worth a watch.) One relevant feature of MATLAB is its global style. The Python concept of importing is not heavily used in MATLAB, and most of MATLAB’s functions are readily available to the user at the top level. Knowing that matplotlib has its roots in MATLAB helps to explain why pylab exists. pylab is a module within the matplotlib library that was built to mimic MATLAB’s global style. It exists only to
bring a number of functions and classes from both NumPy and matplotlib into the namespace, making for an easy transition for former MATLAB users who were not used to needing Ex-MATLAB converts (who are all fine people, I promise!) liked this functionality, because with The
issue here may be apparent to some Python users: using
Internally, there are a ton of potentially conflicting imports being masked within the short pylab source. In fact, using The bottom line is that matplotlib has abandoned this convenience module and now explicitly recommends against using pylab, bringing things more in line with one of Python’s key notions: explicit is better than implicit. Without the need for pylab, we can usually get away with just one canonical import: >>>
While we’re at it, let’s also import NumPy, which we’ll use for generating data later
on, and call >>>
The Matplotlib Object HierarchyOne important big-picture matplotlib concept is its object hierarchy. If you’ve worked
through any introductory matplotlib tutorial, you’ve probably called something like A You can think of the Here’s an illustration of this hierarchy in action. Don’t worry if you’re not completely familiar with this notation, which we’ll cover later on: >>>
Above, we created two variables with >>>
Above, Matplotlib presents this as a figure anatomy, rather than an explicit hierarchy: (In true matplotlib style, the figure above is created in the matplotlib docs here.) Stateful Versus Stateless ApproachesAlright, we need one more chunk of theory before we can get around to the shiny visualizations: the difference between the stateful (state-based, state-machine) and stateless (object-oriented, OO) interfaces. Above, we used Almost all functions from pyplot, such as
Hardcore ex-MATLAB users may choose to word this by saying something like, “
The flow of this process, at a high level, looks like this: Tying these together, most of the
functions from pyplot also exist as methods of the This is easier to see by peeking under the hood. >>>
Calling pyplot is home to a batch of functions that are really just wrappers around matplotlib’s object-oriented interface. For example, with Calling
Similarly, if you take a
few moments to look at the source for top-level functions like Understanding plt.subplots() NotationAlright, enough theory. Now, we’re ready to tie everything together and do some plotting. From here on out, we’ll mostly rely on the stateless (object-oriented) approach, which is more customizable and comes in handy as graphs become more complex. The prescribed way to create a Figure with a single Axes under the OO approach is (not too intuitively) with >>>
Above, we took advantage of iterable unpacking to
assign a separate variable to each of the two results of >>>
We can call its instance methods to manipulate the plot similarly to how we call pyplots functions. Let’s illustrate with a stacked area graph of three time series: >>>
Here’s what’s going on above:
Let’s look at an example with multiple subplots (Axes) within one Figure, plotting two correlated arrays that are drawn from the discrete uniform distribution: >>>
There’s a little bit more going on in this example:
Remember that multiple Axes can be enclosed in or “belong to” a given figure. In the case above, >>>
( Taking this one step further, we could alternatively create a figure that holds a 2x2 grid of >>>
Now, what is >>>
This is reaffirmed by the docstring:
We now need to call plotting methods on each of these >>>
We could’ve also done this with To illustrate some more advanced subplot features, let’s pull some macroeconomic California housing data extracted from a compressed tar archive, using >>>
The “response” variable >>>
Next let’s define a “helper function” that places a text box inside of a plot and acts as an “in-plot title”: >>>
We’re ready to do some plotting. Matplotlib’s Above,
what we actually have is a 3x2 grid. The second argument to >>>
Now, we can proceed as normal, modifying each Axes individually: >>>
Above, Visually, there isn’t much differentiation in color (the y-variable) as we move up and down the y-axis, indicating that home age seems to be a stronger determinant of house value. The “Figures” Behind The ScenesEach time you call >>>
(We could also
use the built-in After the above routine, the current figure is >>>
A useful way to get all of the Figures themselves is with
a mapping of >>>
Be cognizant of this if running a script where you’re creating a group of figures. You’ll want to explicitly close each of them after use to avoid a >>>
A Burst of Color: imshow() and matshow()While Methods that get heavy use are First, let’s create two distinct grids with some fancy NumPy indexing: >>>
Next, we can map
these to their image representations. In this specific case, we toggle “off” all axis labels and ticks by using a dictionary comprehension and passing the result to >>>
Then, we can use a context manager to disable the grid, and call >>>
Plotting in PandasThe pandas library has become popular for not just for enabling powerful data analysis, but also for its handy pre-canned plotting methods. Interestingly though, pandas plotting methods are really just convenient wrappers around existing matplotlib calls. That is, the In turn, remember that We can prove this “chain” of function calls with a bit of introspection. First, let’s construct a plain-vanilla pandas Series, assuming we’re starting out in a fresh interpreter session: >>>
This internal architecture is helpful to know when you are mixing pandas plotting methods with traditional matplotlib calls, which is done below in plotting the moving average of a widely watched financial time series.
>>>
There’s a lot happening above:
Pandas also comes built-out with a smattering of more advanced plots (which could take up an entire tutorial all on their own). However, all of these, like their simpler counterparts, rely on matplotlib machinery internally. Wrapping UpAs shown by some of the examples above, there’s no getting around the fact that matplotlib can be a technical, syntax-heavy library. Creating a production-ready chart sometimes requires a half hour of Googling and combining a hodgepodge of lines in order to fine-tune a plot. However, understanding how matplotlib’s interfaces interact is an investment that can pay off down the road. As Real Python’s own Dan Bader has advised, taking the time to dissect code rather than resorting to the Stack Overflow “copy pasta” solution tends to be a smarter long-term solution. Sticking to the object-oriented approach can save hours of frustration when you want to take a plot from plain to a work of art. More ResourcesFrom the matplotlib documentation:
Third-party resources:
Other plotting libraries:
Appendix A: Configuration and StylingIf you’ve been following along with this tutorial, it’s likely that the plots popping up on your screen look different stylistically than the ones shown here. Matplotlib offers two ways to configure style in a uniform way across different plots:
A matplotlibrc file (Option #1 above) is basically a text file specifying user-customized settings that are remembered between Python sessions. On Mac OS X, this normally resides at ~/.matplotlib/matplotlibrc. Alternatively, you can change your configuration parameters interactively
(Option #2 above). When you >>>
Of these:
With >>>
Notably, the Figure class then uses some of these as its default arguments. Relatedly, a style is just a predefined cluster of custom settings. To view available styles, use: >>>
To set a style, make this call: >>>
Your plots will now take on a new look: This full example is available here. For inspiration, matplotlib keeps some style sheet displays for reference as well. Appendix B: Interactive ModeBehind the scenes, matplotlib also interacts with different backends. A backend is the workhorse behind actually rendering a chart. (On the popular Anaconda distribution, for instance, the default backend is Qt5Agg.) Some backends are interactive, meaning they are dynamically updated and “pop up” to the user when changed. While interactive mode is off by default, you can check its status with >>>
>>>
In some code examples, you may notice the presence of
Below, we make sure that interactive mode is off, which requires that we call >>>
Notably, interactive mode has nothing to do with what IDE you’re using, or whether you’ve enable inline plotting with something like Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Plotting With Matplotlib Can you plot in 3D in Python?We could plot 3D surfaces in Python too, the function to plot the 3D surfaces is plot_surface(X,Y,Z), where X and Y are the output arrays from meshgrid, and Z=f(X,Y) or Z(i,j)=f(X(i,j),Y(i,j)). The most common surface plotting functions are surf and contour. TRY IT!
How do you plot a 3D object in Python?Plot a single point in a 3D space. Step 1: Import the libraries. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D. ... . Step 2: Create figure and axes. fig = plt.figure(figsize=(4,4)) ax = fig.add_subplot(111, projection='3d') ... . Step 3: Plot the point.. Is plotting possible in Python?matplotlib is the most widely used scientific plotting library in Python. Plot data directly from a Pandas dataframe. Select and transform data, then plot it. Many styles of plot are available: see the Python Graph Gallery for more options.
Can I plot a Dataframe in Python?Python has many popular plotting libraries that make visualization easy. Some of them are matplotlib, seaborn, and plotly. It has great integration with matplotlib. We can plot a dataframe using the plot() method.
|