Why is there a semicolon ; after matplotlibs plot() function?

Question:

I’ve seen this a couple of times:

# http://geopandas.org/aggregation_with_dissolve.html
continents.plot(column = 'pop_est', scheme='quantiles', cmap='YlOrRd');

# https://jakevdp.github.io/PythonDataScienceHandbook/04.14-visualization-with-seaborn.html
plt.legend('ABCDEF', ncol=2, loc='upper left');

# https://matplotlib.org/api/pyplot_api.html
x = np.arange(0, 5, 0.1);

It confuses me that it is done very often with matplotlib and also inconsistently.

Is this only an error? Was it in the matplotlib documentation for a while?

Does / did ; have any function at the and of a line in Python? (This suggests the answer is "no", but it does not explain why it is so wide-spread with matplotlib.)

Asked By: Martin Thoma

||

Answers:

As stated in the linked question’s answer, the only purpose of a semicolon in pure Python is to separate statements in a single line.

However, here you observe semi colons at the end of lines, which, indeed, would not serve any purpose in pure Python.

There are mainly two reasons here:

  1. As commented by hpaulj, semicolons are used in MATLAB, and often people now working with Python, matplotlib and related packages are very much used to MATLAB and hence might accidentally type those in. This is the reason for the semicolon accidentally appearing in the third mentioned case (pyplot)

     x = np.arange(0, 5, 0.1);
    

It should be noted that this link refers to an older version in the matplotlib documentation, which in the current version has been corrected.

  1. More importantly, you will often see semicolons being used when code has been initially used in IPython or Jupyter Notebooks. In those cases, the semicolon is, just like in MATLAB, used to prevent output from a code line.

    Enter image description here

So it’s not necessarily related to matplotlib, but in turn matplotlib is often used in one way or the other in notebooks, and notebooks are easily converted to HTML and hence you often find code on websites stemming from such notebooks. This would be the reason for the semicolons in the first and second example case.

From the post Silver BlogGold BlogData Visualization in Python: Matplotlib vs Seaborn:

A handy tip is that whenever matplotlib is executed, the output will
always include a text output that can be very visually unappealing. To
fix this, add a semicolon – ‘;‘ at the end of the last line of code
when executing a code chunk to generate a figure.

Answered By: Alz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.