将迷你图添加到 Pandas 数据框
Adding Sparkline to Pandas Dataframe
我想绘制迷你图并将其附加到我的数据框中。我已经完成了一堆最终 运行 到 Base64 编码输出的示例。我希望使用一种简单的方法,也许使用 matplotlib。我需要可视化每一行的折线图,我不确定是否可以将 plt 图附加到数据框单元格?我的猜测是没有。
我最好的尝试如下:
## Imports
from scipy import stats
import matplotlib.pyplot as plt
%matplotlib inline
import sparklines
import base64
from io import BytesIO
import matplotlib
matplotlib.use("Agg")
## Create example dataset
def sparkline(data, figsize=(4,0.25),**kwags):
data = list(data)
fig,ax = plt.subplots(1,1,figsize=figsize,**kwags)
ax.plot(data)
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
plt.plot(len(data)-1, data[len(data)-1], 'r.')
ax.fill_between(range(len(data)), data, len(data)*[min(data)], alpha=0.1)
img = BytesIO()
plt.savefig(img, transparent=True, bbox_inches='tight')
img.seek(0)
plt.close()
return base64.b64encode(img.read()).decode("UTF-8")
## Create sparkline (output is Base64 sting - Should be linechart)
df = pd.DataFrame(price, columns=['Close'])
df = df.T
df['Trend'] = df.apply(sparkline, axis=1)
pd.set_option('display.max_colwidth', -1)
df
不确定为什么我的脚本没有将 Base64 字符串解码为折线图。有没有简单的方法?
Current Output: Close iVBORw0KGgoAAAANSUhEUgAAAO0AAAAbCAYAAACQhgiLAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAFEElEQVR4nO3afYxcVRnH8c9daBdKMVSpadSYaxRMiQKp+NJgG19AozdUNESiiSb8AdYYNEYhV3xLNIRrQkLUqCghVCNSUFMCvYoCajQR62vUCCnVeCMtGihqsCzQ7u74x3M33Taz0+7MbtuZnu8/mzvnzDPP3bm/8/zOcybrdDoSicTwMHa0E0gkEvMjiTaRGDKSaBOJISOJ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WnG14v6h2Y7i+zf0WXNlUxVPts/AP/EGck28yt9vYK1zD7jb2jjbnVfY7nN/ip9jcji0mpwkn8QohwAmRf68C9citmz+587ydD54zPrXv/qO6p83L+lxxltmt2m4Qq9/5Yu9znViZ5+Ie8UAMwnbcP2CM44ELxSK5ur3ejV/jYSGQR1E7vK77ScIuLxdbkTscKPQMH8dHhOA+hOeLB/89ovKvE1352fxTiPTRed3ZkeFU4SwmcZVwPofDE4MeFS7InjYv6xX226rZrBLHJStEhb1P2JeDmRZf3PaBk0kcy6zFF4ULeFaIcZ15dtyHnIFFu1BHPk8KK3QwjwurdrOw0F9foM9LDCd34UfCOm8Ue8/DrVCjwuShp/Rm5LrHicSoM9K/iEokRpEk2kRiyEiiTSSGjCTaRGLISKJNJIaMJNpEYsj4P1RkeFLWS0WaAAAAAElFTkSuQmCC
名称:趋势,数据类型:object
应该是这样的:
所以我自己解决了这个问题。
我定义了生成迷你图的函数:
def sparkline(data, figsize=(4,0.25),**kwags):
data = list(data)
fig,ax = plt.subplots(1,1,figsize=figsize,**kwags)
ax.plot(data)
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
plt.plot(len(data)-1, data[len(data)-1], 'r.')
ax.fill_between(range(len(data)), data, len(data)*[min(data)], alpha=0.1)
img = BytesIO()
plt.savefig(img, transparent=True, bbox_inches='tight')
img.seek(0)
# plt.show()
plt.close()
return base64.b64encode(img.read()).decode("utf-8")
有了内存中的这个功能,我就能够生成所需的 PNG 图像,然后将它们保存到一个目录中。从 excel 开始工作,我导入了图像。
d2 = pd.DataFrame(price, columns=['Close'])
d2 = d2.T
d2['Trend'] = d2.apply(sparkline, axis=1)
data = str(list(d2['Trend']))
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('C:/Users/Toby/Desktop/IB/Training/Lines/'+str(t)+'.png', 'PNG')
我想绘制迷你图并将其附加到我的数据框中。我已经完成了一堆最终 运行 到 Base64 编码输出的示例。我希望使用一种简单的方法,也许使用 matplotlib。我需要可视化每一行的折线图,我不确定是否可以将 plt 图附加到数据框单元格?我的猜测是没有。
我最好的尝试如下:
## Imports
from scipy import stats
import matplotlib.pyplot as plt
%matplotlib inline
import sparklines
import base64
from io import BytesIO
import matplotlib
matplotlib.use("Agg")
## Create example dataset
def sparkline(data, figsize=(4,0.25),**kwags):
data = list(data)
fig,ax = plt.subplots(1,1,figsize=figsize,**kwags)
ax.plot(data)
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
plt.plot(len(data)-1, data[len(data)-1], 'r.')
ax.fill_between(range(len(data)), data, len(data)*[min(data)], alpha=0.1)
img = BytesIO()
plt.savefig(img, transparent=True, bbox_inches='tight')
img.seek(0)
plt.close()
return base64.b64encode(img.read()).decode("UTF-8")
## Create sparkline (output is Base64 sting - Should be linechart)
df = pd.DataFrame(price, columns=['Close'])
df = df.T
df['Trend'] = df.apply(sparkline, axis=1)
pd.set_option('display.max_colwidth', -1)
df
不确定为什么我的脚本没有将 Base64 字符串解码为折线图。有没有简单的方法?
Current Output: Close iVBORw0KGgoAAAANSUhEUgAAAO0AAAAbCAYAAACQhgiLAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAFEElEQVR4nO3afYxcVRnH8c9daBdKMVSpadSYaxRMiQKp+NJgG19AozdUNESiiSb8AdYYNEYhV3xLNIRrQkLUqCghVCNSUFMCvYoCajQR62vUCCnVeCMtGihqsCzQ7u74x3M33Taz0+7MbtuZnu8/mzvnzDPP3bm/8/zOcybrdDoSicTwMHa0E0gkEvMjiTaRGDKSaBOJISOJNpEYMpJoE4kh48SjncCRIC/rt+Bbut/v/3BFUxX3HtmsEon+OC5Ei8uxFHd2GTsfd+dlfUlTFVvzsj4BZ+NV+Bu2NVUxceRSTSR6k436OW1e1idj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2m4Qq9/5Yu9znViZ5+Ie8UAMwnbcP2CM44ELxSK5ur3ejV/jYSGQR1E7vK77ScIuLxdbkTscKPQMH8dHhOA+hOeLB/89ovKvE1352fxTiPTRed3ZkeFU4SwmcZVwPofDE4MeFS7InjYv6xX226rZrBLHJStEhb1P2JeDmRZf3PaBk0kcy6zFF4ULeFaIcZ15dtyHnIFFu1BHPk8KK3QwjwurdrOw0F9foM9LDCd34UfCOm8Ue8/DrVCjwuShp/Rm5LrHicSoM9K/iEokRpEk2kRiyEiiTSSGjCTaRGLISKJNJIaMJNpEYsj4P1RkeFLWS0WaAAAAAElFTkSuQmCC 名称:趋势,数据类型:object
应该是这样的:
所以我自己解决了这个问题。
我定义了生成迷你图的函数:
def sparkline(data, figsize=(4,0.25),**kwags):
data = list(data)
fig,ax = plt.subplots(1,1,figsize=figsize,**kwags)
ax.plot(data)
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
plt.plot(len(data)-1, data[len(data)-1], 'r.')
ax.fill_between(range(len(data)), data, len(data)*[min(data)], alpha=0.1)
img = BytesIO()
plt.savefig(img, transparent=True, bbox_inches='tight')
img.seek(0)
# plt.show()
plt.close()
return base64.b64encode(img.read()).decode("utf-8")
有了内存中的这个功能,我就能够生成所需的 PNG 图像,然后将它们保存到一个目录中。从 excel 开始工作,我导入了图像。
d2 = pd.DataFrame(price, columns=['Close'])
d2 = d2.T
d2['Trend'] = d2.apply(sparkline, axis=1)
data = str(list(d2['Trend']))
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('C:/Users/Toby/Desktop/IB/Training/Lines/'+str(t)+'.png', 'PNG')