Matplotlib Basemap Equivalent Python 3 - python

Non Code general question: I am running Python 3.5.2 (Anaconda distribution) and new to Python. I want to create a heat map over layed onto map of USA. All searches I've done say use 'basemap' which seems to be unsupported in Python 3. What alternatives are out there (do not want to revert to previous Python).

You can use Seaborn python module it works for python3 as well.
And here is the help regarding heatmap using seaborn.
Or you may use Geoplot python module

geoplot is another library that allows you to create choropleth maps. These can then be overlayed on a webmap using mplleaflet.

Basemap is supported in python 3. With the anaconda install of python 3.7 I used conda install basemap. At this point you might need to set you PROJ_LIB if you are running in the base environment, as shown in the following example script:
import os
os.environ['PROJ_LIB'] = r'C:\Users\YOURUSERNAME\Anaconda3\pkgs\proj4-5.2.0-ha925a31_1\Library\share'
Now you should be able to use basemap in python 3. Here's an example I adapted from Dan Nguyen's github (I removed the Earthquake data and just left the map itself, see the link for neat stuff):
# %matplotlib # in iPython
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
plt.figure(figsize=(14, 8))
earth = Basemap()
earth.bluemarble(alpha=0.42)
earth.drawcoastlines(color='#555566', linewidth=1)
plt.show()
Resultant image:

Related

cannot plot with matplotlib and pandas

I am using OSX (Mojave 10.14.3) and am having a strange issue plotting a pandas (0.24.2) dataframe using matplotlib (3.0.3). I am using python 3.7.3.
So, the code is as:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'name':['john','mary','peter','jeff','bill','lisa','jose'],
'age':[23,78,22,19,45,33,20],
'gender':['M','F','M','M','M','F','M'],
'state':['california','dc','california','dc','california','texas','texas'],
'num_children':[2,0,0,3,2,1,4],
'num_pets':[5,1,0,5,2,2,3]
})
df.plot(kind='scatter',x='num_children',y='num_pets',color='red')
plt.show()
All this does is show an empty window with nothing in it. I was expecting a scatterplot with 7 points. The example is taken from the web tutorial as is.
EDIT
plt.savefig('myfilename.png')
Savefig works.
I am not sure if this will help anyone but I basically had to install python as a framework to make it work. I was using Anaconda, so something like:
conda install python.app
pythonw script.py # note using pythonw
I, then, was able to get the plot to render correctly by using the macosx backend:
import matplotlib as mpl
mpl.use('MacOSX')

how to copy matplotlib figures to clipboard

After plotting the figure, I want to copy it to the clipbaoard instead of saving to figures. I searched the internet and the code does not work, either the required modules only support python 2.x or the program stopped by not well-defined functions.
I am using Python 3.6 in Windows 10. My matplotlib version is 2.0.2.
I tried 'PyGTK: copy matplotlib figure to clipboard'
and got the error: ImportError: Gtk* backend requires pygtk to be installed. I then visited www.pygtk.org/downloads.html to download pygtk/PyGObject (Windows) but it requires python 2.6 or file not found.
Can anyone show how to achieve it?
import matplotlib.pyplot as plt
a = [2,3,6,7,1]
plt.plot(a)
plt.show()

Bokeh doesn't find Bar-chart modules on Raspberry Pi

_I'm trying to make bar-charts with Bokeh to be outputted as .html-files. Everything works fine with simple plotting, but for some reason when i try to run the following code:
from bokeh.charts import Bar, output_file, show
from bokeh.sampledata.autompg import autompg as df
p = Bar(df, label='yr', values='mpg', agg='mean',
title="Average MPG by YR")
output_file("bar.html")_
I end up with an error saying:
ImportError: No module named 'bokeh.charts'
I have installed Pandas, Numpy through pip and they all can be found using the help('modules') command. I've understood that Pandas is required for high-level Bokeh charts and it's been installed through Pip
Pandas version: 0.20.3
Bokeh version: 0.12.9
Python is version 3.4.2
I've tried also different import commands, "from bokeh import *" etc. but nothing seems to work.
In addition to Holoviews, if you just need simple bar charts, these are also now easy to make from the stable bokeh.plotting API, e.g.:
group = df.groupby('cyl')
source = ColumnDataSource(group)
cyl_cmap = factor_cmap('cyl', palette=Spectral5, factors=sorted(df.cyl.unique()))
p = figure(plot_height=350, x_range=group, title="MPG by # Cylinders")
p.vbar(x='cyl', top='mpg_mean', width=1, source=source,
line_color=cyl_cmap, fill_color=cyl_cmap)
bokeh.charts has been deprecated. You can get back the functionality by installing and importing the bkcharts package but this won’t be supported in the future. Bokeh devs recommend checking holoviews (which use bokeh as a possible back-end)

Matplotlib not displaying image

I am trying to use matplotlib to view an image in ipython. However, I solely obtain a description of the image as opposed to seeing the actual image:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> plt.imshow(an_array)
Out[4]: <matplotlib.image.AxesImage at 0x7fb626f063d0>
This is with the backend set to Qt5Agg or TkAgg in .matplotlibrc
I have the same issues whether or not I am working in a conda virtual environment
I am running: Scientific Linux release 6.8 (Carbon), Python 2.7.13, Anaconda 4.3.0 (64-bit)
I have had similar issues on my local computer running MacOSX
I would be most grateful for any advice,
Thanks
Rob
Add %matplotlib inline before import matplotlib.pyplot as plt to enable automatic visualization of your plots when the cell has finished executing.
Note, however, that this works just in iPython notebooks. Normally, you'd need to call plt.show() (without any arguments) to visualize the plots.

Plotting window doesn't show up with pylab [duplicate]

I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
I get no plot window. Any ideas on how to get the plot window to show?
You can type
import pylab
pylab.show()
or better, use ipython -pylab.
Since the use of pylab is not recommended anymore, the solution would nowadays be
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show()
pylab.show() works but blocks (you need to close the window).
A much more convenient solution is to do pylab.ion() (interactive mode on) when you start: all (the pylab equivalents of) pyplot.* commands display their plot immediately. More information on the interactive mode can be found on the official web site.
I also second using the even more convenient ipython -pylab (--pylab, in newer versions), which allows you to skip the from … import … part (%pylab works, too, in newer IPython versions).
Try this:
import matplotlib
matplotlib.use('TkAgg')
BEFORE import pylab
The code snippet below works on both Eclipse and the Python shell:
import numpy as np
import matplotlib.pyplot as plt
# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# Just print x and y for fun
print x
print y
# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)
# Without the line below, the figure won't show
plt.show()
Any errors show up? This might an issue of not having set the backend. You can set it from the Python interpreter or from a config file (.matplotlib/matplotlibrc) in you home directory.
To set the backend in code you can do
import matplotlib
matplotlib.use('Agg')
where 'Agg' is the name of the backend. Which backends are present depend on your installation and OS.
http://matplotlib.sourceforge.net/faq/installing_faq.html#backends
http://matplotlib.org/users/customizing.html
Modern IPython uses the "--matplotlib" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.
ipython --matplotlib
If you encounter an issue in which pylab.show() freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.
Apparently, future calls to pylab.show() will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.
If you are starting IPython with the --pylab option, you shouldn't need to call show() or draw(). Try this:
ipython --pylab=inline
--pylab no longer works for Jupyter, but fortunately we can add a tweak in the ipython_config.py file to get both pylab as well as autoreload functionalities.
c.InteractiveShellApp.extensions = ['autoreload', 'pylab']
c.InteractiveShellApp.exec_lines = ['%autoreload 2', '%pylab']
If you are user of Anaconda and Spyder then best solution for you is that :
Tools
-->
Preferences
-->
Ipython console
-->
Graphic Section
Then in the Support for graphics (Matplotlib) section:
select two avaliable options
and in the Graphics Backend:
select Automatic
Another possibility when using easy_install is that you need to require the most recent version of matplotlib.
Try:
import pkg_resources
pkg_resources.require("matplotlib")
before you import matplotlib or any of its modules.

Categories