Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

geom_image() for plotnine? Enhancement? With chessboard example #869

Open
TerryGamon opened this issue Sep 3, 2024 · 1 comment
Open
Labels

Comments

@TerryGamon
Copy link

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")

image

@sravanpannala
Copy link

sravanpannala commented Jan 10, 2025

Here is an implementation I came up with, which is based on geom_point. I have been using this for months now for .png files. A drawback is that draw_panel directly calls draw_unit. I couldn't make it work with draw_group. Maybe it isn't necessary.

@document
class geom_image(geom):
    """
    Plot Images with plotnine
    Based on geom_point 
    Instead of points, plots images at those points

    Args:
        geom : ggplot geom
    """    
    DEFAULT_AES = {"size": 0.1}#, "color": None, "fill": "#333333",
                   #"linetype": "solid", "size": 0.5 }
    DEFAULT_PARAMS = {"stat": "identity", "position": "identity",
                      "na_rm": False} # no idea if I need this
    REQUIRED_AES = {"x", "y","image"} # just need an image column

    def draw_panel(self, data, panel_params, coord, ax, **params):
        """
        assume only one image per panel,
        """
        data = coord.transform(data, panel_params)
        self.draw_unit(data, panel_params, coord, ax, **params)
    
    @staticmethod
    def draw_group(data, panel_params, coord, ax, **params):
        data = coord.transform(data, panel_params)
        units = "shape"
        for _, udata in data.groupby(units, dropna=False):
            udata.reset_index(inplace=True, drop=True)
            geom_image.draw_unit(udata, panel_params, coord, ax, **params)
    
    @staticmethod
    def draw_unit(data, panel_params, coord, ax, **params):
        for i in range(len(data)):
            img = data["image"].iloc[i]
            zoom = data["size"].iloc[i]
            ab = AnnotationBbox(
                OffsetImage(plt.imread(img), zoom=zoom),
                (data["x"].iloc[i], data["y"].iloc[i]),
                frameon=False,
            )
            ax.add_artist(ab)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants