Matplotlib Visual Studio Code



Jupyter (formerly IPython Notebook) is an open-source project that lets you easily combine Markdown text and executable Python source code on one canvas called a notebook. Visual Studio Code supports working with Jupyter Notebooks natively, as well as through Python code files. This topic covers the native support available for Jupyter Notebooks and demonstrates how to:

  • Create, open, and save Jupyter Notebooks
  • Work with Jupyter code cells
  • View, inspect, and filter variables using the Variable explorer and Data viewer
  • Connect to a remote Jupyter server
  • Debug a Jupyter notebook

Setting up your environment

To work with Jupyter notebooks, you must activate an Anaconda environment in VS Code, or another Python environment in which you've installed the Jupyter package. To select an environment, use the Python: Select Interpreter command from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

Matplotlib and Visual Studio Code. The commands on the following page has been performed and tested with the following versions: Ubuntu 18.04 LTS 64bits; Linux 4.15.0-76-generic; Python 3.6.9; Visual Studio Code. Note: If you're looking to get started with Python in Visual Studio Code, refer to the tutorial Getting Started with Python in VS Code. Select and activate an environment. By default, the Python extension looks for and uses the first Python interpreter it finds in the system path.

Once the appropriate environment is activated, you can create and open a Jupyter Notebook, connect to a remote Jupyter server for running code cells, and export a Jupyter Notebook as a Python file.

Note: By default, the Visual Studio Code Python extension will open a Jupyter Notebook (.ipynb) in the Notebook Editor. If you want to disable this behavior you can turn it off in settings. (Python > Data Science: Use Notebook Editor).

Create or open a Jupyter Notebook

You can create a Jupyter Notebook by running the Jupyter: Create Blank New Jupyter Notebook command from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) or by creating a new .ipynb file in your workspace. When you select the file, the Notebook Editor is launched allowing you to edit and run code cells.

  • Visual Studio code中numpy, matplotlib包的安装及测试 1 安装.
  • Install matplotlib by entering its name into the search field and then selecting the Run command: pip install matplotlib option. This will install matplotlib, as well as any packages it depends on (in this case that includes numpy). Consent to elevation if prompted to do so.

If you have an existing Jupyter Notebook, you can open it in the Notebook Editor by double-clicking on the file and opening with Visual Studio Code, through the Visual Studio Code, or using the Command Palette Jupyter: Open in Notebook Editor command.

Once you have a Notebook created, you can run a code cell using the green run icon above the cell and the output will appear directly below the code cell.

Trusted Notebooks

It's possible for malicious source code to be contained in a Jupyter Notebook. With that in mind, to help protect you, any Notebook that's not created with VS Code on your local machine (or explicitly set to Trusted by you) is considered Not Trusted. When a Notebook is Not Trusted, VS Code will not render Markdown cells or display the output of code cells within the Notebook. Instead, just the source of Markdown and code cells will be shown. The Notebook is essentially in read-only mode, with toolbars disabled and no ability to edit the file, until you set it as Trusted.

Note: Before setting a Notebook as Trusted, it is up to you to verify that the source code and Markdown are safe to run. VS Code does not perform any sanitizing of Markdown, it merely prevents it from being rendered until a Notebook is marked as Trusted to help protect you from malicious code.

When you first open a Notebook that's Not Trusted, the following notification prompt is displayed.

If you select Trust, the Notebook will be trusted going forward. If you opt not to trust the Notebook, then Not Trusted will be displayed in the toolbar and the Notebook will remain in a read-only state as described previously. If you select Trust all notebooks, you will be taken to settings, where you can specify that all Notebooks opened in VS Code be trusted. That means you will no longer be prompted to trust individual notebooks and harmful code could automatically run.

You can relaunch the trust notification prompt after reviewing the Notebook by clicking on the Not Trusted status.

Save your Jupyter Notebook

You can save your Jupyter Notebook using the keyboard combo Ctrl+S or through the save icon on the Notebook Editor toolbar.

Note: At present, you must use the methods discussed above to save your Notebook. The File>Save menu does not save your Notebook, just the toolbar icon or keyboard command.

Export your Jupyter Notebook

You can export a Jupyter Notebook as a Python file (.py), a PDF, or an HTML file. To export, just click the convert icon on the main toolbar. You'll then be presented with file options from the Command Palette.

Note: For PDF export, you must have TeX installed. If you don't, you will be notified that you need to install it when you select the PDF option. Also, be aware that if you have SVG-only output in your Notebook, they will not be displayed in the PDF. To have SVG graphics in a PDF, either ensure that your output includes a non-SVG image format or else you can first export to HTML and then save as PDF using your browser.

Work with code cells in the Notebook Editor

The Notebook Editor makes it easy to create, edit, and run code cells within your Jupyter Notebook.

Create a code cell

By default, a blank Notebook will have an empty code cell for you to start with and an existing Notebook will place one at the bottom. Add your code to the empty code cell to get started.

Code cell modes

While working with code cells a cell can be in three states, unselected, command mode, and edit mode. The current state of a cell is indicated by a vertical bar to the left of a code cell. When no bar is visible, the cell is unselected.

An unselected cell isn't editable, but you can hover over it to reveal additional cell specific toolbar options. These additional toolbar options appear directly below and to the left of the cell. You'll also see when hovering over a cell that an empty vertical bar is present to the left.

When a cell is selected, it can be in two different modes. It can be in command mode or in edit mode. When the cell is in command mode, it can be operated on and accept keyboard commands. When the cell is in edit mode, the cell's contents (code or Markdown) can be modified.

When a cell is in command mode, the vertical bar to the left of the cell will be solid to indicate it's selected.

When you're in edit mode, the vertical bar will have diagonal lines.

To move from edit mode to command mode, press the ESC key. To move from command mode to edit mode, press the Enter key. You can also use the mouse to change the mode by clicking the vertical bar to the left of the cell or out of the code/Markdown region in the code cell.

Add additional code cells

Code cells can be added to a Notebook using the main toolbar, a code cell's vertical toolbar, the add code cell icon at the bottom of the Notebook, the add code cell icon at the top of the Notebook (visible with hover), and through keyboard commands.

Using the plus icon in the main toolbar will add a new cell directly below the currently selected cell. Using the add cell icons at the top and bottom of the Jupyter Notebook, will add a code cell at the top and bottom respectively. And using the add icon in the code cell's toolbar, will add a new code cell directly below it.

When a code cell is in command mode, the A key can be used to add a cell above and the B can be used to add a cell below the selected cell.

Select a code cell

The selected code cell can be changed using the mouse, the up/down arrow keys on the keyboard, and the J (down) and K (up) keys. To use the keyboard, the cell must be in command mode.

Run a single code cell

Once your code is added, you can run a cell using the green run arrow and the output will be displayed below the code cell.

You can also use key combos to run a selected code cell.

Matplotlib
  • Ctrl+Enter runs the currently selected cell
  • Shift+Enter runs the currently selected cell and, if a cell is not already present, inserts a new cell immediately below (focus moves to the below cell in command mode)
  • Alt+Enter runs the currently selected cell and inserts a new cell immediately below (focus moves to new cell in edit mode).

These keyboard combos can be used in both command and edit modes.

Run multiple code cells

Running multiple code cells can be accomplished in a number of ways. You can use the double arrow in the toolbar of the Notebook Editor to run all cells within the Notebook or the run icons with directional arrows to run all cells above or below the current code cell.

Run code by line

To help diagnose issues with your Notebook code, run-by-line lets you step through the code of a cell in a line-by-line fashion. While stepping through code you can view the state of variables at each step via the variable explorer or hover your mouse over variables to see data tips.

To start a session, just click the run-by-line icon to the right of the run cell icon on the cell's toolbar.

Once in a run-by-line session, you can run the currently highlighted line of code by pressing the icon again. To exit, just click the stop button next to the run-by-line icon in the cell.

Move a code cell

Moving code cells up or down within a Notebook can be accomplished using the vertical arrows beside each code cell. Hover over the code cell and then click the up arrow to move the cell up and the down arrow to move the cell down.

Delete a code cell

Deleting a code cell can be accomplished by hovering over a code cell and using the delete icon in the code cell toolbar or through the keyboard combo dd when the selected code cell is in command mode.

Undo your last change

Code

You can use the z key to undo your previous change, for example, if you've made an accidental edit you can undo it to the previous correct state, or if you've deleted a cell accidentally you can recover it.

Switch between code and Markdown

The Notebook Editor allows you to easily change code cells between Markdown and code. By default a code cell is set for code, but just click the Markdown icon (or the code icon, if Markdown was previously set) in the code cell's toolbar to change it.

Once Markdown is set, you can enter Markdown formatted content to the code cell. Once you select another cell or toggle out of the content selection, the Markdown content is rendered in the Notebook Editor.

You can also use the keyboard to change the cell type. When a cell is selected and in command mode, the M key switches the cell type to Markdown and the Y key switches the cell type to code.

Clear output or restart/interrupt the kernel

If you'd like to clear the code cell output or restart/interrupt the kernel, you can accomplish that using the main Notebook Editor toolbar.

Enable/Disable line numbers

You can enable or disable line numbering within a code cell using the L key.

IntelliSense support in the Jupyter Notebook Editor

The Python Jupyter Notebook Editor window has full IntelliSense – code completions, member lists, quick info for methods, and parameter hints. You can be just as productive typing in the Notebook Editor window as you are in the code editor.

Variable explorer and data viewer

Within the Python Notebook Editor, it's possible to view, inspect, and filter the variables within your current Jupyter session. By clicking the Variables icon in the top toolbar after running code and cells, you'll see a list of the current variables, which will automatically update as variables are used in code. Iphone app free.

For additional information about your variables, you can also double-click on a row or use the Show variable in data viewer button next to the variable to see a more detailed view of a variable in the Data Viewer. Once open, you can filter the values by searching over the rows.

Note: Variable explorer is enabled by default, but can be turned off in settings (Python > Data Science: Show Jupyter Variable Explorer).

Plot viewer

The Plot Viewer gives you the ability to work more deeply with your plots. In the viewer you can pan, zoom, and navigate plots in the current session. You can also export plots to PDF, SVG, and PNG formats.

Visual studio code matplotlib not showing

Within the Notebook Editor window, double-click any plot to open it in the viewer, or select the plot viewer button on the upper left corner of the plot (visible on hover).

Note: There is support for rendering plots created with matplotlib and Altair.

Debug a Jupyter Notebook

If you need additional debug support in order to diagnose an issue in your code cells, you can export it as a Python file. Once exported as a Python file, the Visual Studio Code debugger lets you step through your code, set breakpoints, examine state, and analyze problems. Using the debugger is a helpful way to find and correct issues in notebook code. To debug your Python file:

  1. In VS Code, if you haven't already, activate a Python environment in which Jupyter is installed.

  2. From your Jupyter Notebook (.ipynb) select the convert button in the main toolbar.

    Once exported, you'll have a .py file with your code that you can use for debugging.

  3. After saving the .py file, to start the debugger, use one of the following options:

    • For the whole Notebook, open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and run the Jupyter: Debug Current File in Python Interactive Window command.
    • For an individual cell, use the Debug Cell adornment that appears above the cell. The debugger specifically starts on the code in that cell. By default, Debug Cell just steps into user code. If you want to step into non-user code, you need to uncheck Data Science: Debug Just My Code in the Python extension settings (⌘, (Windows, Linux Ctrl+,)).
  4. To familiarize yourself with the general debugging features of VS Code, such as inspecting variables, setting breakpoints, and other activities, review VS Code debugging.

  5. As you find issues, stop the debugger, correct your code, save the file, and start the debugger again.

  6. When you're satisfied that all your code is correct, use the Python Interactive window to export the Python file as a Jupyter Notebook (.ipynb).

Connect to a remote Jupyter server

You can offload intensive computation in a Jupyter Notebook to other computers by connecting to a remote Jupyter server. Once connected, code cells run on the remote server rather than the local computer.

To connect to a remote Jupyter server:

  1. Run the Jupyter: Specify local or remote Jupyter server for connections command from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

  2. When prompted to Pick how to connect to Jupyter, select Existing: Specify the URI of an existing server.

  3. When prompted to Enter the URI of a Jupyter server, provide the server's URI (hostname) with the authentication token included with a ?token= URL parameter. (If you start the server in the VS Code terminal with an authentication token enabled, the URL with the token typically appears in the terminal output from where you can copy it.) Alternatively, you can specify a username and password after providing the URI.

Note: For added security, Microsoft recommends configuring your Jupyter server with security precautions such as SSL and token support. This helps ensure that requests sent to the Jupyter server are authenticated and connections to the remoter server are encrypted. For guidance about securing a notebook server, see the Jupyter docs.

Jupyter (formerly IPython Notebook) is an open-source project that lets you easily combine Markdown text and executable Python source code on one canvas called a notebook. Visual Studio Code supports working with Jupyter Notebooks natively, as well as through Python code files. This topic covers the support offered through Python code files and demonstrates how to:

  • Work with Jupyter-like code cells
  • Run code in the Python Interactive Window
  • View, inspect, and filter variables using the Variable explorer and data viewer
  • Connect to a remote Jupyter server
  • Debug a Jupyter notebook
  • Export a Jupyter notebook

To work with Jupyter notebooks, you must activate an Anaconda environment in VS Code, or another Python environment in which you've installed the Jupyter package. To select an environment, use the Python: Select Interpreter command from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

Once the appropriate environment is activated, you can create and run Jupyter-like code cells, connect to a remote Jupyter server for running code cells, and export Python files as Jupyter notebooks.

Jupyter code cells

You define Jupyter-like code cells within Python code using a # %% comment:

Note: Make sure to save the code shown above in a file with a .py extension.

When the Python extension detects a code cell, it adds Run Cell and Debug Cell CodeLens adornments. The first cell also includes Run Below and all subsequent cells include Run Above:

Note: By default, Debug Cell just steps into user code. If you want to step into non-user code, you need to uncheck Data Science: Debug Just My Code in the Python extension settings (⌘, (Windows, Linux Ctrl+,)).

Run Cell applies to only the one code cell. Run Below, which appears on the first cell, runs all the code in the file. Run Above applies to all the code cells up to, but not including, the cell with the adornment. You would use Run Above, for example, to initialize the state of the runtime environment before running that specific cell.

Selecting a command starts Jupyter (if necessary, which might take a minute), then runs the appropriate cell(s) in the Python Interactive window:

You can also run code cells using (Ctrl+Enter) or the Python: Run Selection/Line in Python Terminal command (Shift+Enter). After using this command, the Python extension automatically moves the cursor to the next cell. If you're in the last cell in the file, the extension automatically inserts another # %% delimiter for a new cell, mimicking the behavior of a Jupyter notebook.

You can also click in the margin to the left of line numbers to set breakpoints. Then you can use Debug Cell to start a debugging session for that code cell. The debugger stops execution at breakpoints and allows you to step through code one line at a time and inspect variables (see Debugging for details).

Additional commands and keyboard shortcuts

The following table lists additional commands and keyboard shortcuts supported when working with code cells.

Matplotlib inline visual studio code
CommandKeyboard shortcut
Python: Go to Next CellCtrl+Alt+]
Python: Go to Previous CellCtrl+Alt+[
Python: Extend Selection by Cell AboveCtrl+Shift+Alt+[
Python: Extend Selection by Cell BelowCtrl+Shift+Alt+]
Python: Move Selected Cells UpCtrl+; U
Python: Move Selected Cells DownCtrl+; D
Python: Insert Cell AboveCtrl+; A
Python: Insert Cell BelowCtrl+; B
Python: Insert Cell Below PositionCtrl+; S
Python: Delete Selected CellsCtrl+; X
Python: Change Cell to CodeCtrl+; C
Python: Change Cell to MarkdownCtrl+; M

Python Interactive window

The Python Interactive window, mentioned in the previous section, can be used as a standalone console with arbitrary code (with or without code cells). To use the window as a console, open it with the Jupyter: Create Interactive Window command from the Command Palette. You can then type in code, using Enter to go to a new line and Shift+Enter to run the code.

To use the window with a file, use the Jupyter: Run Current File in Python Interactive Window command from the Command Palette.

IntelliSense

The Python Interactive window has full IntelliSense – code completions, member lists, quick info for methods, and parameter hints. You can be just as productive typing in the Python Interactive window as you are in the code editor.

Plot Viewer

The Plot Viewer gives you the ability to work more deeply with your plots. In the viewer you can pan, zoom, and navigate plots in the current session. Microsoft windows mac os. You can also export plots to PDF, SVG, and PNG formats.

Within the Python Interactive window, double-click any plot to open it in the viewer, or select the expand button on the upper left corner of the plot.

Note: The Python Interactive window supports rendering plots created with matplotlib and Altair.

Live Share for Python Interactive

The Python Interactive window also supports Visual Studio Live Share for real-time collaboration. Live Share lets you co-edit and co-debug while sharing audio, servers, terminals, diffs, comments, and more.

This feature requires the Live Share extensions to be installed on both host and guest machines.

Variable explorer and data viewer

Within the Python Interactive window, it's possible to view, inspect, and filter the variables within your current Jupyter session. By expanding the Variables section after running code and cells, you'll see a list of the current variables, which will automatically update as variables are used in code.

For additional information about your variables, you can also double-click on a row or use the Show variable in data viewer button to see a more detailed view of a variable in the Data Viewer. Once open, you can filter the values by searching over the rows.

Note: Variable explorer is enabled by default, but can be turned off in settings (Python > Data Science: Show Jupyter Variable Explorer).

Connect to a remote Jupyter server

You can offload intensive computation in a Jupyter notebook to other computers by connecting to a remote Jupyter server. Once connected, code cells run on the remote server rather than the local computer.

To connect to a remote Jupyter server:

  1. Run the Jupyter: Specify local or remote Jupyter server for connections command from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

  2. Select how you would like to connect to a Jupyter server.

  3. If working remotely, provide the server's URI (hostname) with the authentication token included with a ?token= URL parameter when prompted. (If you start the server in the VS Code terminal with an authentication token enabled, the URL with the token typically appears in the terminal output from where you can copy it.) Alternatively, you can specify a username and password after providing the URI.

  4. The Python Interactive window indicates where code is run by displaying the URI (which is blurred out in the image below):

Note: For added security, Microsoft recommends configuring your Jupyter server with security precautions such as SSL and token support. This helps ensure that requests sent to the Jupyter server are authenticated and connections to the remoter server are encrypted. For guidance about securing a notebook server, see the Jupyter docs.

Convert Jupyter notebooks to Python code file

When you've activated an environment with Jupyter installed, you can open a Jupyter notebook file (.ipynb) in VS Code and then convert it to Python code. Once you've converted the file, you can run the code as you would with any other Python file and also use the VS Code debugger. Opening and debugging notebooks in VS Code is a convenient way to find and resolve code bugs, which is difficult to do directly in a Jupyter notebook.

When you open a notebook file, Visual Studio Code will open it in the Notebook Editor automatically. Use the convert icon on the toolbar to convert the Notebook (.ipynb) file to a Python file (.py).

Select the convert icon followed by 'Python Script', wait a few seconds, and then VS Code opens the converted notebook in an untitled file. The notebook's cells are delimited in the Python file with # %% comments; Markdown cells are converted wholly to comments preceded with # %% [markdown], and render as HTML in the interactive window alongside code and output such as graphs:

Note: The first time you run code cells in a Python file, the Python extension starts a Jupyter server. It may take some time for the server to start up and for the Python Interactive window to appear with the results of the code.

Debug a Jupyter notebook

The Visual Studio Code debugger lets you step through your code, set breakpoints, examine state, and analyze problems. Using the debugger is a helpful way to find and correct issues in notebook code.

  1. In VS Code, activate a Python environment in which Jupyter is installed, as described at the beginning of this article.

  2. Import the notebook's .ipynb file into VS Code as described in the previous section. (Download the file first if you're using a cloud-based Jupyter environment such as Azure Notebooks.)

  3. To start the debugger, use one of the following options:

    • For the whole notebook, open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and run the Jupyter: Debug Current File in Python Interactive Window command.
    • For an individual cell, use the Debug Cell adornment that appears above the cell. The debugger specifically starts on the code in that cell. By default, Debug Cell just steps into user code. If you want to step into non-user code, you need to uncheck Data Science: Debug Just My Code in the Python extension settings (⌘, (Windows, Linux Ctrl+,)).
  4. To familiarize yourself with the general debugging features of VS Code, such as inspecting variables, setting breakpoints, and other activities, review VS Code debugging.

  5. As you find issues, stop the debugger, correct your code, save the file, and start the debugger again.

  6. When you're satisfied that all your code is correct. Save the file, then export the notebook as described in the following section. You can then upload the notebook to your normal Jupyter environment.

Export a Jupyter notebook

Vscode No Module Named Matplotlib

In addition to opening a Jupyter notebook, you can also use one of the following commands from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) to export content from a Python file in VS Code to a Jupyter notebook (with the .ipynb extension).

  • Jupyter: Export Current Python File as Jupyter Notebook: creates a Jupyter notebook from the contents of the current file, using the # %% and # %% [markdown] delimiters to specify their respective cell types.
  • Jupyter: Export Current Python File and Output as Jupyter Notebook: creates a Jupyter notebook from the contents of the current file and includes output from code cells.
  • Jupyter: Export Interactive Window as Jupyter Notebook: creates a Jupyter notebook from the contents of the Python Interactive window.

Visual Studio Code Tutorial Pdf

After exporting the contents, VS Code displays a prompt through which you can open the notebook in a browser.





Comments are closed.