Some tricks collected from the SO and the web
Images
How to use an image as a background
import numpy as np
import matplotlib.pyplot as plt
0)
np.random.seed(= np.random.uniform(0.0,10.0,15)
x = np.random.uniform(0.0,10.0,15)
y = 'lena.jpg'
datafile = plt.imread(datafile)
img =1)
plt.scatter(x,y,zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
plt.imshow(img, zorder plt.show()
caveat This requires you know where the image corners need to be!
sources:
Creating a pictogram
import matplotlib.pyplot as plt
from pywaffle import Waffle
= {'Democratic': 48, 'Republican': 46, 'Libertarian': 3}
data = plt.figure(
fig =Waffle,
FigureClass=5,
rows=data,
values=["#232066", "#983D3D", "#DCB732"],
colors={'loc': 'upper left', 'bbox_to_anchor': (1, 1)},
legend='child',
icons=12,
font_size=True
icon_legend
) plt.show()
note:
PyWaffle supports Font Awesome icons in the chart. plotly is an alternative. Sources: - How to make a pictogram / icon chart?
Icons
Adding images to the axes of a plot
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage,AnnotationBbox
def get_flag(name):
= "data/flags/Flags/flags/flags/24/{}.png".format(name.title())
path = plt.imread(path)
im return im
def offset_image(coord, name, ax):
= get_flag(name)
img = OffsetImage(img, zoom=0.72)
im = ax
im.image.axes = AnnotationBbox(im, (coord, 0), xybox=(0., -16.), frameon=False,
ab ='data', boxcoords="offset points", pad=0)
xycoords
ax.add_artist(ab)= ["Norway", "Spain", "Germany", "Canada", "China"]
countries = [20, 15, 30, 5, 26]
valuesA = plt.subplots()
fig, ax range(len(countries)), valuesA, width=0.5,align="center")
ax.bar(range(len(countries)))
ax.set_xticks(
ax.set_xticklabels(countries)='x', which='major', pad=26)
ax.tick_params(axisfor i, c in enumerate(countries):
offset_image(i, c, ax) plt.show()
Plot images at the end of a bar chart
import matplotlib.pyplot as plt
from iso3166 import countries
import matplotlib.image as mpimg
def pos_image(x, y, pays, haut):
= countries.get(pays).alpha2.lower()
pays = "/usr/share/iso-flags-png-320x240"
fichier += f"/{pays}.png"
fichier = mpimg.imread(fichier)
im = 4 / 3
ratio = ratio * haut
w
ax.imshow(im,=(x - w, x, y, y + haut),
extent=2)
zorder
'seaborn')
plt.style.use(= plt.subplots()
fig, ax = [('France', 10), ('USA', 9), ('Spain', 5), ('Italy', 5)]
liste_pays = [p[1] for p in liste_pays]
X = [p[0] for p in liste_pays]
Y = .8
haut = ax.barh(y=Y, width=X, height=haut, zorder=1)
r = [rectangle.get_y() for rectangle in r]
y_bar for pays, y in zip(liste_pays, y_bar):
1], y, pays[0], haut)
pos_image(pays[ plt.show()
and a second solution which put the flag in the axes if the bar is too short.
import numpy as np
import requests
from io import BytesIO
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
def offset_image(x, y, label, bar_is_too_short, ax):
= requests.get(f'https://www.countryflags.io/{label}/flat/64.png')
response = plt.imread(BytesIO(response.content))
img = OffsetImage(img, zoom=0.65)
im = ax
im.image.axes = -25
x_offset if bar_is_too_short:
= 0
x = AnnotationBbox(im, (x, y), xybox=(x_offset, 0), frameon=False,
ab ='data', boxcoords="offset points", pad=0)
xycoords
ax.add_artist(ab)= ['CW', 'CV', 'GW', 'SX', 'DO']
labels = ['crimson', 'dodgerblue', 'teal', 'limegreen', 'gold']
colors = 2 ** np.random.randint(2, 10, len(labels))
values = 0.9
height =labels, width=values, height=height, color=colors, align='center', alpha=0.8)
plt.barh(y= values.max()
max_value for i, (label, value) in enumerate(zip(labels, values)):
=value < max_value / 10, ax=plt.gca())
offset_image(value, i, label, bar_is_too_short=0.15)
plt.subplots_adjust(left plt.show()
Annotaions
Add outline arond flagged items in a plotly candlestick chart
import pandas as pd
import plotly.graph_objects as go
= pd.DataFrame({"data_minu": ['30/10 09:00','30/10 09:05','30/10,09:10','30/10 09:15','30/10 09:20','30/10 09:25','30/10 09:30','30/10 09:35','30/10 09:40','30/10 09:45'],
df "Open":['10','17','23','20','8','22','24','25','29','22'],
"High":['21','27','25','29','24','27','28','32','29','25'],
"Low":['6','12','18','9','5','8','24','18','15','10'],
"Close":['17','24','22','10','21','25','26','30','18','10'],
"Flag": ['0','1','1','1','0','1','1','1','0','0']})
= go.Figure(data=[go.Candlestick(x=tickvals, #df['data_minu'],
fig open=df['Open'], high=df['High'],
=df['Low'], close=df['Close'])
low
]) =[k*0.5 for k in range(len(df))]
tickvals =list(df["data_minu"])
ticktext=False, xaxis_tickvals=tickvals, xaxis_ticktext=ticktext)
fig.update_layout(xaxis_rangeslider_visiblefor k, flag in enumerate(df['Flag']):
if int(flag):
dict(type='rect',
fig.add_shape(='x', yref='y',
xref='below',
layer= tickvals[k]-0.2, y0 = float(df.loc[k, 'Low'])-1,
x0 = tickvals[k]+0.2, y1 = float(df.loc[k, 'High'])+1,
x1 ='orange', #'RoyalBlue',
fillcolor=0.35)) opacity
scatterpolt with icons
library(rgdal)
library(png)
# load icons in PNG format
<- download.file('http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Status-weather-clouds-icon.png', destfile = 'icon1.png', mode = 'wb')
iconfile1 <- readPNG('icon1.png')
icon1 <- download.file('http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Status-weather-showers-scattered-icon.png', destfile = 'icon2.png', mode = 'wb')
iconfile2 <- readPNG('icon2.png')
icon2
# load shapefile
<- readOGR("DZA", "DZA_adm0")
al
# make up some points
library(sp)
set.seed(613)
<- spsample (al, 3, type='random')
dat
# need to offset the x/y location for the icon (depends on desired icon size)
<- 2
offset plot(al)
rasterImage(icon1, coordinates(dat)[1,1]-offset, coordinates(dat)[1,2]-offset, coordinates(dat)[1,1]+offset, coordinates(dat)[1,2]+offset)
rasterImage(icon2, coordinates(dat)[2,1]-offset, coordinates(dat)[2,2]-offset, coordinates(dat)[2,1]+offset, coordinates(dat)[2,2]+offset)
rasterImage(icon1, coordinates(dat)[3,1]-offset, coordinates(dat)[3,2]-offset, coordinates(dat)[3,1]+offset, coordinates(dat)[3,2]+offset)
points(dat)
Citation
BibTeX citation:
@online{bochman2021,
author = {Bochman, Oren},
title = {Python {Graphs}},
date = {2021-08-29},
url = {https://orenbochman.github.io/posts/2021/2021-09-16-python-graphs/2021-09-14-python-graphs.html},
langid = {en}
}
For attribution, please cite this work as:
Bochman, Oren. 2021. “Python Graphs.” August 29, 2021. https://orenbochman.github.io/posts/2021/2021-09-16-python-graphs/2021-09-14-python-graphs.html.