user7044174
user7044174

Reputation:

Setting Image background for a line plot in matplotlib

I am trying to set a background image to a line plot that I have done in matplotlib. While importing the image and using zorder argument also, I am getting two seperate images, in place of a single combined image. Please suggest me a way out. My code is --

import quandl
import pandas as pd
import sys, os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import itertools

def flip(items, ncol):
    return itertools.chain(*[items[i::ncol] for i in range(ncol)])

df = pd.read_pickle('neer.pickle')
rows = list(df.index)
countries = ['USA','CHN','JPN','DEU','GBR','FRA','IND','ITA','BRA','CAN','RUS']
x = range(len(rows))
df = df.pct_change()

fig, ax = plt.subplots(1)
for country in countries:
	ax.plot(x, df[country], label=country)

plt.xticks(x, rows, size='small', rotation=75)
#legend = ax.legend(loc='upper left', shadow=True)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show(1)

plt.figure(2)
im = plt.imread('world.png')
ax1 = plt.imshow(im, zorder=1)
ax1 = df.iloc[:,:].plot(zorder=2)
handles, labels = ax1.get_legend_handles_labels()
plt.legend(flip(handles, 2), flip(labels, 2), loc=9, ncol=12)
plt.show()

So in the figure(2) I am facing problem and getting two separate plots

Upvotes: 0

Views: 2411

Answers (2)

Anil_M
Anil_M

Reputation: 11453

In order to overlay background image over plot, we need imshow and extent parameter from matplotlib.

Here is an condensed version of your code. Didn't have time to clean up much.

First a sample data is created for 11 countries as listed in your code. It is then pickled and saved to a file (since there is no pickle file data).

import quandl
import pandas as pd
import sys, os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import itertools

from scipy.misc import imread



countries = ['USA','CHN','JPN','DEU','GBR','FRA','IND','ITA','BRA','CAN','RUS']

df_sample = pd.DataFrame(np.random.randn(10, 11), columns=list(countries))
df_sample.to_pickle('c:\\temp\\neer.pickle')

Next the pickle file is read and we create bar plot directly from pandas

df = pd.read_pickle('c:\\temp\\neer.pickle')
my_plot = df.plot(kind='bar',stacked=True,title="Plot Over Image")
my_plot.set_xlabel("countries")
my_plot.set_ylabel("some_number")

Next we use imread to read image into plot.

img = imread("c:\\temp\\world.png")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.imshow(img,zorder=0,  extent=[0.1, 10.0, -10.0, 10.0])
plt.show()

Here is an output plot with image as background. As stated this is crude and can be improved further. enter image description here

Upvotes: 1

Diziet Asahi
Diziet Asahi

Reputation: 40697

You're creating two separate figures in your code. The first one with fig, ax = plt.subplots(1) and the second with plt.figure(2)

If you delete that second figure, you should be getting closer to your goal

Upvotes: 0

Related Questions