Reputation: 7446
Community,
Say I have created a scatter plot with Python's matplotlib:
plt.scatter(x, y)
Now, is there a way to add colored boxes on the axis (between given x-values, e.g.,: add a green box from x=-0.2 to x=0, add a ...) like this:
Including the text labels (at the mid-range I guess).
I am not even sure how to get started on this one to be honest (besides making the scatter plot).
Question Can anyone at least direct me to a feature of matplotlib that does this (or any other Python package)?
Your help is much appreciated.
Upvotes: 0
Views: 1795
Reputation: 5364
You probably want to go with matplotlib's text() function. Maybe something like this,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 100)
y = np.sin(2*np.pi * x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'o')
ax.set_xlim(-0.2, 1.2)
ax.set_ylim(-1.5, 1.5)
x_ticks = ax.get_xticks()
y_ticks = ax.get_yticks()
# use len(x_ticks)-1 number of colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'orange']
for i, x_tick in enumerate(x_ticks[:-1]):
ax.text(x_tick+0.03, y_ticks[0]-0.165, "text %i"%i,
bbox={'fc':colors[i], 'pad':10})
This code returns this image. You can adjust the padding and x,y position as necessary to achieve the exact look you're going for.
Upvotes: 1
Reputation: 3842
fig = plt.figure(figsize=(6,4))
plt.plot(np.arange(0,7,1),np.arange(0,7,1),linestyle='--', marker='o', color='b')
rect1 = plt.Rectangle((1.5,1.5),(0.7),(0.5), facecolor="grey",edgecolor="black",alpha=0.8)
rect2 = plt.Rectangle((2.5,2.5),(0.7),(0.5), facecolor="yellow",edgecolor="black",alpha=0.8)
rect3 = plt.Rectangle((3.5,3.5),(0.7),(0.5), facecolor="k",edgecolor="black",alpha=0.8)
plt.gca().add_patch(rect1)
plt.gca().add_patch(rect2)
plt.gca().add_patch(rect3)
plt.text(1.65,1.65,r"Grey",fontsize = 10,zorder = 5,color = 'k',fontweight = 'bold')
plt.text(2.55,2.65,r"Yellow",fontsize = 10,zorder = 5,color = 'k',fontweight = 'bold')
plt.text(3.555,3.65,r"Black",fontsize = 10,zorder = 5,color = 'white',fontweight = 'bold')
Upvotes: 1