'How do I change the backend in CoCalc to show a matplotlib scatter graph?

I have a program that is working fine locally, but I need to use it in CoCalc on the cloud to share with a group. Everything works fine until the end, when I want to create a scatter graph, in standard way. There are a bunch of other specs, but essentially, it's just

plt.scatter(x, y, color = 'blue')
plt.show()

Nothing tricky. But in Cocalc, it tells me "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure."

Here are the imports from the beginning of the file:

import nltk
import pandas as pd
import matplotlib.pyplot as plt 
import numpy as np

I've searched for this error and tried the solutions I've found, such as importing tkinter. So, for instance, if I change the headers to

import nltk
import tkinter as tk
import pandas as pd
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt 
import numpy as np

I get a different error: "Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running."

I've seen instructions about pip installations and such, but a) I'm not sure the installations would make everything work for my group, and b) CoCalc generally has most of the standard packages ready to go, so maybe that's not the problem?

Obviously, I'm not experienced with these issues, so help is much appreciated.



Solution 1:[1]

If you're using a Jupyter notebook in CoCalc, then the above will just work fine. Here's an example:

https://cocalc.com/wstein/support/matplotlib-scatter-in-jupyter

If you're writing all of your code as part of a Python program (so, e.g., .py files) and running this from a Terminal, CoCalc will also fully support Tk and this working! However, you have to start a new X11 desktop session in CoCalc by clicking +New --> "Linux Graphical X11 Desktop", then run your Python program from the terminal in the upper left. You'll see any windows that pop up in the main window off to the right.

See https://cocalc.com/wstein/support/scatter-matplotlib-x11

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 William Stein