Open
Description
I would appreciate something like geom_image -library(ggimage)-
https://github.com/GuangchuangYu/ggimage
for plotnine.
geom_image allows to place an image at aes(x,y)
geom_image(
mapping = NULL,
data = NULL,
stat = "identity",
position = "identity",
inherit.aes = TRUE,
na.rm = FALSE,
by = "width",
nudge_x = 0,
...
)
Not difficult to achieve? Here is an example using plt:
https://github.com/TerryGamon/Chess4Python
import pandas as pd
import plotnine as p9
import matplotlib.pyplot as plt
import matplotlib
def drawPosition(fen):
figuren = pd.DataFrame({
"f": ["p", "r", "n", "b", "q", "k", "P", "R", "N", "B", "Q", "K"],
"gif": [
"bp1024.gif", "br1024.gif", "bn1024.gif", "bb1024.gif", "bq1024.gif",
"bk1024.gif", "wP1024.gif", "wR1024.gif", "wN1024.gif", "wB1024.gif",
"wQ1024.gif", "wK1024.gif"
]
})
def square_color(s, z):
return "black" if (s + z) % 2 == 0 else "white"
def fen_to_dataframe(fen):
board_fen = fen.split()[0]
board = []
rows = board_fen.split('/')
for z, row in enumerate(rows):
s = 1
for char in row:
if char.isdigit():
for _ in range(int(char)):
color = square_color(s, 8 - z)
board.append({'s': s, 'z': 8 - z, 'f': None, 'c': color})
s += 1
else:
color = square_color(s, 8 - z)
board.append({'s': s, 'z': 8 - z, 'f': char, 'c': color})
s += 1
df = pd.DataFrame(board)
return df
df_board = fen_to_dataframe(fen).merge(figuren, on='f', how='left')
p=(p9.ggplot(df_board)
+p9.geom_tile(p9.aes(x='s-.5',y='z-.5', fill='c'))
#+p9.geom_text(p9.aes(x='s-.5',y='z-.5', label='f'), size=15)
+p9.theme_bw()
+p9.theme(figure_size=[8,8])
+p9.coord_fixed()
+p9.scale_fill_manual(values=['darkgray','lightgray'])
+p9.theme(axis_line=p9.element_blank())
+p9.theme(panel_background=p9.element_blank())
+p9.theme(axis_text=p9.element_blank())
+p9.theme(axis_ticks=p9.element_blank())
+p9.theme(panel_grid=p9.element_blank())
+p9.labs(x='',y='')
+p9.theme(legend_position='none')
)
fig = p.draw()
ax = fig.axes[0]
dff_board = df_board.dropna()
# here geom_image happens
for i, row in dff_board.iterrows():
img = matplotlib.offsetbox.OffsetImage(
plt.imread(row['gif']),
zoom = 0.06)
ax.add_artist(matplotlib.offsetbox.AnnotationBbox(img,
(row['s']-.5 ,row['z']-.5)
,pad = 0.0
,frameon =False
)
)
return fig
drawPosition("r1b1k1nr/p2p1pNp/n2B4/1p1NP2P/6P1/3P1Q2/P1P1K3/q5b1")