Как изменить оси matplotlib

от admin

matplotlib.pyplot.axis#

Convenience method to get or set some axis properties.

The axis limits to be set. This can also be achieved using

If a bool, turns axis lines and labels on or off. If a string, possible values are:

Turn on axis lines and labels. Same as True .

Turn off axis lines and labels. Same as False .

Set equal scaling (i.e., make circles circular) by changing axis limits. This is the same as ax.set_aspect(‘equal’, adjustable=’datalim’) . Explicit data limits may not be respected in this case.

Set equal scaling (i.e., make circles circular) by changing dimensions of the plot box. This is the same as ax.set_aspect(‘equal’, adjustable=’box’, anchor=’C’) . Additionally, further autoscaling will be disabled.

Set limits just large enough to show all data, then disable further autoscaling.

Automatic scaling (fill plot box with data).

‘scaled’ with axis limits equal to data limits.

Square plot; similar to ‘scaled’, but initially forcing xmax-xmin == ymax-ymin .

Whether observers are notified of the axis limit change. This option is passed on to set_xlim and set_ylim .

Использование библиотеки Matplotlib. Как изменять интервал осей

По умолчанию библиотека Matplotlib подбирает масштаб графика так, чтобы в окне уместились все точки, однако с помощью функций xlim() и ylim() можно задавать интервал по осям X и Y соответственно, который мы хотим отобразить более подробно.

Следующий пример создает список точек, расположенных на интервале от -50 до 50 по оси X, однако мы ограничиваем просматриваемую область интервалом от -10 до 30.

import matplotlib. pyplot as plt
import numpy as np

if __name__ == ‘__main__’ :
# Интервал изменения переменной по оси X
xmin = — 50.0
xmax = 50.0

# Количество точек на графике
xcount = 301

# Создадим список координат по оси X на отрезке [-xmin; xmax], включая концы
x = np. linspace ( xmin , xmax , xcount )

# Вычислим значение функции в заданных точках
y = np. sinc ( x / np. pi )

# Нарисуем одномерный график с использованием стиля
plt. plot ( x , y )

# На графике будет показан только участок от -10 до 30 по оси X
plt. xlim ( — 10 , 30 )

# Покажем окно с нарисованным графиком
plt. show ( )

Результат получается следующий:

Следующий пример использует также функцию ylim(), чтобы расширить область по вертикали от -1 до 2:

import matplotlib. pyplot as plt
import numpy as np

if __name__ == ‘__main__’ :
# Интервал изменения переменной по оси X
xmin = — 50.0
xmax = 50.0

# Количество точек на графике
xcount = 301

# Создадим список координат по оси X на отрезке [-xmin; xmax], включая концы
x = np. linspace ( xmin , xmax , xcount )

# Вычислим значение функции в заданных точках
y = np. sinc ( x / np. pi )

# Нарисуем одномерный график с использованием стиля
plt. plot ( x , y )

# На графике будет показан только участок от -10 до 30 по оси X
plt. xlim ( — 10 , 30 )

# На графике будет показан участок от -1 до 2 по оси Y
plt. ylim ( — 1 , 2 )

# Покажем окно с нарисованным графиком
plt. show ( )

В результате мы увидим следующую картину:

Если мы хотим изменить только верхний или нижний предел на осях, то можно воспользоваться именованными параметрами xmin или xmax для функции xlim() и ymin или ymax для функции ylim().

Следующий пример изменяет только нижний предел по оси X и верхний по оси Y:

import matplotlib. pyplot as plt
import numpy as np

if __name__ == ‘__main__’ :
# Интервал изменения переменной по оси X
xmin = — 50.0
xmax = 50.0

# Количество точек на графике
xcount = 301

# Создадим список координат по оси X на отрезке [-xmin; xmax], включая концы
x = np. linspace ( xmin , xmax , xcount )

# Вычислим значение функции в заданных точках
y = np. sinc ( x / np. pi )

# Нарисуем одномерный график с использованием стиля
plt. plot ( x , y )

# На графике будет показан только участок от -10 до 30 по оси X
plt. xlim ( xmin = — 10 )

# На графике будет показан участок от -1 до 2 по оси Y
plt. ylim ( ymax = 2 )

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Поворот меток осей в Matplotlib

Введение Matplotlib — одна из наиболее широко используемых библиотек визуализации данных в Python. Большая часть популярности Matplotlib связана с его параметрами настройки — вы можете настроить практически любой элемент из его иерархии объектов. В этом уроке мы рассмотрим, как повернуть текст / метки галочки на графике Matplotlib. Создание графика Давайте сначала создадим простой график: import matplotlib.pyplot as plt import numpy as np x = np.arange (0, 10, 0.1) y = np.sin (x) plt.plot (x, y) plt. показывать()

Время чтения: 5 мин.

Вступление

Matplotlib — одна из наиболее широко используемых библиотек визуализации данных в Python. Большая часть популярности Matplotlib связана с его параметрами настройки — вы можете настроить практически любой элемент из его иерархии объектов .

В этом уроке мы рассмотрим, как вращать текст / метки галочки на графике Matplotlib .

Создание сюжета

Давайте сначала создадим простой сюжет:

простой графикmatplotlib

Поворот меток с отметками оси X в Matplotlib

Теперь давайте посмотрим, как мы можем здесь вращать метки оси X. Есть два способа сделать это — изменить его на уровне рисунка с помощью plt.xticks() или изменить его на уровне осей, используя tick.set_rotation() индивидуально, или даже используя ax.set_xticklabels() и ax.xtick_params() .

Начнем с первого варианта:

Здесь мы установили rotation xticks на 45, что означает наклон на 45 градусов против часовой стрелки:

Примечание. Эта функция, как и все остальные здесь, должна вызываться после plt.plot() , чтобы метки не могли оказаться обрезанными или неуместными.

Другой вариант — получить текущий Axes и вызвать для него ax.set_xticklabels() . Здесь мы можем установить метки, а также их поворот:

Примечание. Для того, чтобы этот подход сработал, вам необходимо вызвать plt.draw() перед доступом или установкой меток X-галочки. Это связано с тем, что метки заполняются после рисования графика, в противном случае они возвращают пустые текстовые значения.

В качестве альтернативы мы могли бы tick s в ax.get_xticklabels() . Затем мы можем вызвать tick.set_rotation() для каждого из них:

Это также приводит к:

И, наконец, вы можете использовать ax.tick_params() и установить там поворот метки:

Это также приводит к:

Поворот меток с отметками оси Y в Matplotlib

Точно такие же шаги можно применить для меток в виде галочки оси Y.

Во-первых, вы можете изменить его на уровне рисунка с помощью plt.yticks() или в Axes-lebel, используя tick.set_rotation() или манипулируя ax.set_yticklabels() и ax.tick_params() .

Начнем с первого варианта:

Как и в прошлый раз, это устанавливает rotation yticks на 45 градусов:

Теперь поработаем напрямую с объектом Axes

То же самое относится и к этому plt.draw() перед этим вызовом, чтобы он работал правильно.

Теперь давайте итерацию по списку tick s и set_rotation() по каждому из них:

Это также приводит к:

И, наконец, вы можете использовать ax.tick_params() и установить там поворот метки:

Это также приводит к:

Повернуть даты по размеру в Matplotlib

Чаще всего люди ставят галочки на своих графиках потому, что они содержат даты. Даты могут быть длинными, и даже с небольшим набором данных они начнут перекрываться и быстро станут нечитаемыми.

Конечно, вы можете вращать их, как мы делали раньше, обычно наклон в 45 градусов решает большинство проблем, а наклон на 90 градусов освобождает еще больше.

Однако в Matplotlib есть еще один вариант поворота и фиксации дат, который даже проще, чем предыдущие методы — fig.autofmt__date() .

Эта функция может использоваться как fig.autofmt_xdate() или fig.autofmt_ydate() для двух разных осей.

Давайте посмотрим, как мы можем использовать это в наборе данных погоды Сиэтла :

Заключение

В этом руководстве мы рассмотрели несколько способов поворота текста / меток оси в графике Matplotlib, включая особый способ форматирования и подгонки дат.

Если вас интересует визуализация данных и вы не знаете, с чего начать, обязательно ознакомьтесь с нашим комплектом книг по визуализации данных в Python <.ebook-link>:

Визуализация данных в Python

. <.col-md-8 .col-xs-12 .my-auto>Станьте опасными с визуализацией данных

✅ 30-дневная гарантия возврата денег без вопросов

✅ от начального до продвинутого

✅ Регулярно обновляется бесплатно (последнее обновление в апреле 2021 г.)

✅ Обновлено с бонусными ресурсами и руководствами . . .

Визуализация данных в Python с помощью Matplotlib и Pandas — это книга, предназначенная для абсолютных новичков в работе с Pandas и Matplotlib с базовыми знаниями Python и позволяющая им создать прочную основу для расширенной работы с этими библиотеками — от простых графиков до анимированных трехмерных графиков с интерактивными кнопки.

Он служит подробным руководством, которое научит вас всему, что вам нужно знать о Pandas и Matplotlib, в том числе о том, как создавать типы графиков, которые не встроены в саму библиотеку.

Книга «Визуализация данных в Python» , книга для начинающих и средних разработчиков Python, проведет вас через простые манипуляции с данными с помощью Pandas, охватит основные библиотеки построения графиков, такие как Matplotlib и Seaborn, и покажет, как использовать преимущества декларативных и экспериментальных библиотек, таких как Altair. В частности, на протяжении 11 глав эта книга охватывает 9 библиотек Python: Pandas, Matplotlib, Seaborn, Bokeh, Altair, Plotly, GGPlot, GeoPandas и VisPy.

Он служит уникальным практическим руководством по визуализации данных в виде множества инструментов, которые вы можете использовать в своей карьере.

Matplotlib invert y axis

In this Python tutorial, we will discuss Matplotlib invert y axis in python. Here we will cover different examples related to inverting of the y-axis using matplotlib. And we will also cover the following topics:

  • Matplotlib invert y axis
  • Matplotlib invert y axis subplots
  • Matplotlib invert x and y axis
  • Matplotlib barh invert y axis
  • Matplotlib invert secondary y axis
  • Matplotlib 3D invert y axis
  • Matplotlib flip y axis label
  • Matplotlib invert y axis imshow

If you are new to python Matplotlir, check out, How to install matplotlib python.

Table of Contents

Matplotlib invert y axis

In this section, we learn about how to invert the y-axis in matplotlib in Python. Now before starting the topic firstly, we discuss what does invert mean here:

Invert means reverse or flip the order

To understand more clearly let’s take a common example:

Suppose the y-axis starts from 0 to 10 and you want to start it from 10 to 0. So in that cases, we invert or flip the axes of the plot.

In matplotlib, we can invert the y-axis of a graph using different methods. The following are the different methods used for reversing the y-axis are as below.

  • Using invert_yaxis() method
  • Using ylim() method
  • Using axis() method
Читать:
Как изменить форматирование текста в ворде

By using invert_yaxis() method

To invert Y-axis, we can use invert_yaxis() method.

Syntax of the method is as below:

Example: (Without inverting axis)

  • In the above example, we import the matplotlib.pyplot and numpy library.
  • After this we define data using np.arrange() and np.sin() method.
  • Next, we use the plt.plot() method to draw the plot.
  • By using plt.title() we define the title of the plot.
  • plt.show() method is used to generate the plot on the user screen.

matplotlib invert y axis

Look at the y-axis: Here it starts from -1.00 and ends at 1.00

Example: (With inverting axis)

  • In the above example, we include the plt.gca() method to get current axes.
  • After this, we use the ax.invert_yaxis() method to invert or reverse the y-axis of the plot.

matplotlib reverse y axis

Look at the y-axis: Here it starts from 1.00 and ends at -1.00

Conclusion: By using invert_yaxis() method we can reverse the y-axis of the plot.

By using ylim() method

ylim() method is also used to invert axes of a plot in Matplotlib. Generally, this method is used to set limits for the axes.

But if we set the minimum value as the upper limit and maximum value as the lower limit we can revert the axes.

The syntax of the ylim() method is as below:

Here bottom and top specify the tuple of the new y-axis limits.

Let’s see an example to understand it more clearly:

  • In the above example, firstly we import numpy and matplotlib.pyplot library.
  • Next, we define the data and by using the plt.subplot() method we create subplots.
  • Now we use the plot() method to draw a simple plot.
  • plt.ylim() method is used to invert the y-axis here we pass max and min as a parameter.

invert y axis in matplotlib

Conclusion: In the normal plot, the y-axis starts from 1 and ends at 5. And In the inverted plot, the y-axis starts from 5 and ends at 1.

By using axis() method

The axis() method is also used to revert axes in Matplotlib. Basically, this method is used to set the minimum and maximum values of the axes.

But if we set the minimum value as the upper limit and the maximum value as the lower limit we can get inverted axes.

The syntax of the axis() method is as below:

Let’ see an example:

  • Here we import matplotlib.pyplot and numpy library and define data using np.arrange() and np.tan() method.
  • plt.subplots() method is used for creating subplots.
  • Then we use the plot() method to plot a graph and the set_title() method is used to add a title to the plot.
  • By using the plt.axis() method we revert the axes and here we pass the max and min values of the y and x axes.

matplotlib flip y axis

Matplotlib invert y axis subplots

Here we will discuss how to invert the y-axis of the specific subplot if we draw multiple plots in a figure area in Python matplotlib.

We use the invert_yaxis() method to flip the y-axis of the subplot.

Let’s understand the concept with the help of an example:

  • In the above example, we plot multiple plots in a figure area. And we want to invert the y-axis of the specific plot.
  • Here we use the invert_yaixs() method to flip the y-axis of the plot.
  • We use the invert_yaxis() method with the third plot.

matplotlib invert y axis subplots

Matplotlib invert x and y axis

Here we are going to learn how to invert the x-axis and y-axis of the plot in Python matplotlib.

By using invert_xaxis() and invert_yaxis() method we can flip the x-axis and y-axis respectively.

The syntax is as given below:

Let’s see an example related to this concept:

  • In the above example, we import numpy and matplotlib libraries.
  • After this, we define data on x and y coordinates.
  • By using the plt.subplots() method we create subplots in a figure area.
  • Next, we use the plot() method to plot a graph and the set_title() method to set the title of the plot.
  • Then we use plt.gca() method to get current axes of the plot.
  • By using the invert_yaxis() and the invert_xaxis() method we flip the axes of the plot.
  • In last, we use the tight_layout() method to automatically set the plots and the show() method to display the plot on the user’s screen.

matplotlib invert x and y axis

Matplotlib barh invert y axis

Here we are going to learn how we invert the y-axis of the horizontal bar chart using matplotlib in Python. Firstly, we have to know how to plot a horizontal bar chart.

The syntax to plot the horizontal bar chart is as below:

Here x represents the x-axis coordinates and y represents the height of the bars.

The syntax to invert the y-axis of the barh chart is as given below:

Example:

  • In the above example, we first import the numpy and matplotlib.pyplot library.
  • Next, we define data.
  • By using the plt.barh() method we create a horizontal bar chart.
  • By using the plt.gca() method we get the current axes of the plot.
  • Then we use the invert_yaxis() method to flip the y-axis of the plot.

matplotlib barh invert y axis

Matplotlib invert secondary y axis

Here we are going to learn how we can invert the secondary y-axis in matplotlib in Python. Firstly, we have to understand what does secondary y-axis means and when we need it.

Once in a while, we need two x-axes or y-axes to get more insights into the data. At that moment we need to create secondary axes.

In python, matplotlib provides the functionality to create a plot that has two y-axes, and even we can provide different labels to both.

We can create a plot with two different y-axes by using two different axes objects. And to create different axes objects we use the twinx() method.

Let’s see an example where we invert the secondary y-axis:

  • In the above example, we import important libraries such as numpy and matplotlib.pyplot.
  • Next, we create data by using the np.arange() method here we define data between 0 to 10 with the difference of 3.5 at the x-axis.
  • Then by using plt.subplots() methods we create subplots.
  • By using the twinx() we create another axes object for the secondary y-axis.
  • set_xlabel() and set_ylabel() methods are used for adding labels on the axes.
  • By using the tight_layout() and show() method we define the layout and show the plot.

matplotlib invert secondary y axis

invert secondary y axis matplotlib

Matplotlib 3D invert y axis

In this section, we are going to study how to invert a 3D plot in Matplotlib in Python.

The syntax to create a 3D plot and invert the y-axis:

Here x, y, and z are the coordinates points.

Let’s see an example related to this:

  • In the above example, we import important libraries such as matplotlib.pyplot, and mplot3D.
  • Next, we use the plot() method to plot a graph in a figure area.
  • By using the ylim() method we invert the y-axis of the plot. In function, we pass the max and min of y1 coordinates.

matplotlib 3D invert y axis

Matplotlib flip y axis label

Here we are going to learn to flip labels at the y-axis in Matplotlib in Python. By using the ylabel() method we can add the label at the y-axis and flip it.

Example:

  • In the above example, we import matplotlib.pyplot library for visualization.
  • Next, we define the data and use the plt.plot() method to draw a plot.
  • By using plt.ylabel() method we set the label at the y-axis and flip it horizontally by passing the rotation argument. Here we set the value of rotation to 0.

matplotlib flip y axis label

flip y axis label matplotlib

Matplotlib invert y axis imshow

Here we learn to invert the y-axis in the imshow() method in Python Matplotlib. Firstly, understand what does imshow does:

inshow() method shows an image of a color-mapped or 3D RGB array.

The syntax of the inshow() method is given below:

The parameters used above are described as below:

  • X: specify data of the image.
  • cmap: specifies colormap or registered colormap name.
  • norm: It is a normalized instance used to scale data.
  • aspect: Used to control the aspect ratio of the axes.
  • interpolation: It is an interpolation method used to display images.
  • alpha: specify the intensity of the color.
  • vmin, vmax: specify the range of the color bar.
  • origin: Used to place [0,0] index of the array in the upper left or lower corner of the axes.
  • extent: It is a bounding box in data coordinates.
  • filternorm: Used for the antigrain image resize filter.
  • filterrad: specify the filter radius for filters.
  • url: set the URL of the axes image.

Example:

  • Here we define data using the np.array() method and use the imshow() method to plot the image of the colormap.
  • We pass the parameter origin to flip the y-axis and set its value to lower.

matplotlib invert y axis imshow

You may like the following Python Matplotlib tutorials:

In this Python tutorial, we have discussed the “Matplotlib invert y axis” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib invert y axis
  • Matplotlib invert y axis subplots
  • Matplotlib invert x and y axis
  • Matplotlib barh invert y axis
  • Matplotlib invert secondary y axis
  • Matplotlib 3D invert y axis
  • Matplotlib flip y axis label
  • Matplotlib invert y axis imshow

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Похожие статьи