Do Not Print Plot

I have a requirement to create multiple plots, one such plot’s code is here.

import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'],
                   'Val': [np.random.rand() for _ in range(6)],
                   })

sns.set_style('whitegrid')
plt.figure(figsize=(6, 4))
sns.barplot(df, x='Label', y='Val', color='steelblue')
plt.xlabel('Bin', fontsize=9)
plt.ylabel('Value', fontsize=9)
plt.title('Trend', fontsize=11)
plt.tight_layout()

all_plots = dict()
buffer = BytesIO()
plt.savefig(buffer, format='png', bbox_inches='tight')
buffer.seek(0)
all_plots['p1'] = buffer

I do not want to print these plots when running the codes in Jupyter, but to save them in another ‘object’ which I can use later to save the images to an excel file.

However, running above code prints the plot, how do I turn-off the “printing”?

3

You can use plt.close()

Or use %%capture at the start of your cell.
Even %%capture myplot and next cell use myplot() to display the plot.

2

Expanding on the first part of rehaqds excellent answer to include how you’d link this to your other object:

As rehaqds covers, you can use plt.close() to not have an open plot object when Jupyter hits the end of the cell, and so it won’t display it. But how do you use that later?

You’d probably want to assign the plot figure to a variable so you can use it later. In fact, that let’s you assign it to another object or display it later.

Example adapted from your code

For using .figure to assign that or display it later you need to assign the plot to a variable, like so. (For more information see here and here and here and here.)
In your case it would look like this in a cell near the start:

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'],
                   'Val': [np.random.rand() for _ in range(6)],
                   })

sns.set_style('whitegrid')
p = plt.figure(figsize=(6, 4))
sns.barplot(df, x='Label', y='Val', color='steelblue')
plt.xlabel('Bin', fontsize=9)
plt.ylabel('Value', fontsize=9)
plt.title('Trend', fontsize=11)
plt.tight_layout()
plt.close()

Besides the addition of plt.close() suggested by rehaqds to close the plot object you created, the other change p = plt.figure(figsize=(6, 4)) (besides making the code an actual minimal reproducible example, see under ‘Help others reproduce the problem’ here) gives us a handle to invoke later.

If you just wanted to redisplay, it in a later cell, you can put p.figure in a cell and see the plot, or use display(p.figure) if it isn’t the last expression in your cell. In your case, you want to assign it to an object. So it would happen like the following in a later cell:

all_plots = dict()
all_plots[1]= p.figure

With that other object assigned, you can also use all_plots[1] in a cell, or the related display(all_plots[1]).
I believe that is what the OP actually wanted.


For sake of completeness here is the code for a cell for the second part of rehaqds’ suggestions:

%%capture mycapplot
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'Label': ['a', 'b', 'c', 'd', 'e', 'f'],
                   'Val': [np.random.rand() for _ in range(6)],
                   })

sns.set_style('whitegrid')
plt.figure(figsize=(6, 4))
sns.barplot(df, x='Label', y='Val', color='steelblue')
plt.xlabel('Bin', fontsize=9)
plt.ylabel('Value', fontsize=9)
plt.title('Trend', fontsize=11)
plt.tight_layout()

You can then in other cells use mycapplot.show() to display it later mycapplot.show(), based on my answer here that includes more context and references. Or mycapplot() as rehaqds points out.

However, using type(mycapplot) you can see that mycapplot is a IPython.utils.capture.CapturedIO object and not a matplotlib plot figure as you seem to want to store for later saving the figure object. In other words, it is more along the lines of Jupyter output, i.e., an image in the .ipynb code, at this point and not a matplotlib plot. It seems downstream of that.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật