在jupyter-notebook中,我只能将图表限制在表格中,也许有人可以在下面的代码中解决这个问题。至少在下一个截图中展示的那样,可以方便地进行绘图缩放和拖动。
![enter image description here](https://istack.dev59.com/txD1w.webp)
代码:
import pandas as pd
import matplotlib.pyplot as plt
import mpld3
from IPython.display import display_html
from bs4 import BeautifulSoup
import inspect
plt.ioff()
def getFig():
iris_df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
fig, ax = plt.subplots()
for species, group in iris_df.groupby('species'):
ax.scatter(group['sepal_length'], group['sepal_width'], label=species)
ax.set_xlabel('Sepal Length')
ax.set_ylabel('Sepal Width')
ax.legend()
return fig
def get_html_df(caption="iris_df.groupby('species').mean()"):
iris_df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
html_df = iris_df.groupby('species')[['sepal_length','sepal_width']].mean()\
.style.set_table_attributes("style='display:inline'")\
.set_caption(caption)._repr_html_()
return html_df
def main(fig,
term = 3,
head="Plot", file="deleteme.jpg", caption="HTML-repr's caption tag",
width=300.0, height=300.0
):
html_plot = main_mpld3(fig, width=width, height=height)
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
kwargs = {arg: values[arg] for arg in args}
[kwargs.pop(key, None) for key in ["fig", "term"]]
match term:
case 1:
mpld3.enable_notebook()
case 2:
html_plot = fig2file2html(plt=plt, **kwargs)
case 3:
html_plot = fig2file2html(html_plot=html_plot, **kwargs)
plt.close()
return html_plot
def main_mpld3(fig, width, height):
html_plot = mpld3.fig_to_html(fig)
html_plot = editHTML(html_plot, width, height)
return html_plot
def editHTML(html_plot, width, height):
soup = BeautifulSoup(html_plot, 'html.parser')
aux = soup.prettify()
toMatch = '"width": 640.0, "height": 480.0'
toReplace = f'"width": {width}, "height": {height}'
modified_html = aux.replace(toMatch, toReplace)
toMatch = '"drawstyle": "default"'
toReplace = '"drawstyle": "inline"'
modified_html = modified_html.replace(toMatch, toReplace)
toMatch = '<style>\n</style>'
toReplace = ''
modified_html = modified_html.replace(toMatch, toReplace)
soup = BeautifulSoup(modified_html, 'html.parser')
aux = soup.prettify()
return aux
def fig2file2html(plt=None, html_plot=None, head="Plot", file="deleteme.jpg", caption="HTML-repr's caption tag",
width=300.0, height=300.0):
if (plt is None) and (html_plot is None):
return Error
if plt is not None:
plt.savefig(file)
html_img = f'<img src={file} alt="" border=3 height={height} width={width}></img>'
if html_plot is not None:
hr = 4*" "
html_img = hr + html_plot + hr
html_plot= html_img.replace("<img", "<img style='display:inline ")
html_plot= f"""<div style='display:inline'>
{html_img}
</div>
"""
html_plot= f"""<table style='display:inline'>
<caption>{caption}</caption>
<tr><th>{head}</th><tr>
<tr><td>
{html_img}
</td></tr>
</table>
"""
return html_plot
def test01():
fig = getFig()
html_df = get_html_df()
html_plot = main(fig)
print("2 dfs inline:")
display_html(html_df + html_df, raw=True)
print("df and plot inline:")
display_html(html_df + html_plot, raw=True)
def test02():
fig = getFig()
html_df = get_html_df(caption="")
html_plot = main(fig,
term = 3,
head="", file="deleteme.jpg", caption="",
width=650.0, height=650.0,
)
display_html(html_df + html_plot, raw=True)
test02()