Matplotlib python ширина графика

Как изменить размер графика в Matplotlib на Python

В визуализации данных график – это наиболее эффективный способ представления данных. Если его не описать в подробном виде, это может показаться сложным. Python имеет Matplotlib, который используется для представления данных в форме построения графиков.

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

Метод 1: используя set_figheight() и set_figwidth()

Пользователь может использовать set_figheight() для изменения высоты и set_figwidth() для изменения ширины графика.

# first, import the matplotlib library import matplotlib.pyplot as plot # The values on x-axis x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The values on y-axis y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # Now, name the x and y axis plot.xlabel('X - AXIS') plot.ylabel('Y - AXIS') #Then, plot the line plot with its default size print("The plot is plotted in its default size: ") plot.plot(x_axis, y_axis) plot.show() # Now, plot the line plot after changing the size of its width and height K = plot.figure() K.set_figwidth(5) K.set_figheight(2) print("The plot is plotted after changing its size: ") plot.plot(x_axis, y_axis) plot.show()
The plot is plotted in its default size: Использование set_figheight() и set_figwidth() - доThe plot is plotted after changing its size: Использование set_figheight() и set_figwidth() - после

Метод 2: с помощью функции figsize()

Функция figsize() принимает два параметра, а именно ширину и высоту в дюймах. По умолчанию значения ширины = 6,4 дюйма и высоты = 4,8 дюйма.

Plot.figure(figsize =(x_axis, y_axis)

Где x_axis – ширина, а y_axis – высота в дюймах.

# First, import the matplotlib library import matplotlib.pyplot as plot # The values on x-axis x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The values on y-axis y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] #Then, plot the line plot with its default size print("The plot is plotted in its default size: ") plot.plot(x_axis, y_axis) plot.show() # Now, plot the line plot after changing the size of figure to 3 X 3 plot.figure(figsize =(3, 3)) print("The plot is plotted after changing its size: ") plot.plot(x_axis, y_axis) plot.show()
The plot is plotted in its default size: Использование функции figsize() - доThe plot is plotted after changing its size: Использование функции figsize() - после

Метод 3: изменив rcParams по умолчанию

Пользователь может навсегда изменить размер фигуры по умолчанию в соответствии со своими потребностями, установив файл figure.figsize.

# First, import the matplotlib library import matplotlib.pyplot as plot # The values on x-axis x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # The values on y-axis y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # now, name the x axis plot.xlabel('X - AXIS') # name the y axis plot.ylabel('Y - AXIS') #Then, plot the line plot with its default size print("The plot is plotted in its default size: ") plot.plot(x_axis, y_axis) plot.show() # Now, change the rc parameters and plot the line plot after changing the size. plot.rcParams['figure.figsize'] = [3, 3] print("The plot is plotted after changing its size: ") plot.plot(x_axis, y_axis) plot.show() plot.scatter(x_axis, y_axis) plot.show()
The plot is plotted in its default size: Изменение размера фигуры по умолчанию - доThe plot is plotted after changing its size: Изменение размера фигуры по умолчанию - после Изменение 

Источник

Читайте также:  Целый остаток от деления python

Как увеличить размер графика в Matplotlib

Как увеличить размер графика в Matplotlib

Вы можете использовать следующий синтаксис, чтобы увеличить размер одного графика в Matplotlib:

import matplotlib.pyplot as plt #define figure size in (width, height) for a single plot plt.figure(figsize=(3,3)) 

И вы можете использовать следующий синтаксис, чтобы увеличить размер всех графиков Matplotlib в записной книжке:

import matplotlib.pyplot as plt #define figure size in (width, height) for all plots plt.rcParams ['figure.figsize'] = [10, 7] 

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1: увеличение размера одного графика Matplotlib

Предположим, мы создаем следующий линейный график в Matplotlib:

import matplotlib.pyplot as plt #define x and y x = [1, 6, 10] y = [5, 13, 27] #create plot of x and y plt.plot (x, y) plt.show() 

По умолчанию (ширина, высота) графика Matplotlib (6.4, 4.8).

Однако мы можем использовать следующий синтаксис, чтобы увеличить размер графика до любых размеров, которые нам нужны:

import matplotlib.pyplot as plt #define plot size plt.figure(figsize=(5,8)) #define x and y x = [1, 6, 10] y = [5, 13, 27] #create plot of x and y plt.plot (x, y) plt.show() 

Пример 2: увеличение размера всех графиков Matplotlib

В следующем коде показано, как установить размер графика для всех графиков Matplotlib в записной книжке:

import matplotlib.pyplot as plt #define plot size for all plots plt.rcParams ['figure.figsize'] = [10, 4] #define first dataset x = [1, 6, 10] y = [5, 13, 27] #create first plot plt.plot (x, y) plt.show() #define second dataset x2 = [1, 6, 10] y2 = [5, 19, 12] #create second plot plt.plot (x2, y2) plt.show() 

Обратите внимание, что оба графика имеют ширину и высоту, указанные аргументами rcParams .

Источник

How to Change Plot and Figure Size in Matplotlib

How to Change Plot and Figure Size in Matplotlib Cover Image

In this tutorial, you’ll learn how to change the plot and figure sizes in Matplotlib. Data visualization is a valuable tool to help you communicate your data. Being able to customize exactly how your plots are sized gives you the flexibility to produce your desired results. This allows you to produce print-ready visualizations.

Читайте также:  Birthday Reminders for August

By the end of this tutorial, you’ll have learned:

  • How to change the plot and figure size using measurements in inches
  • How to set the DPI of a plot and figure
  • How to change the size of a plot by a factor of its size

Loading a Sample Plot

To follow along with this tutorial line by line, copy and paste the code below into your favourite code editor. We’ll be using a simple plot for this tutorial, in order to really focus on how to change the figure size of your plot in Matplotlib.

# Loading a Sample Plot import matplotlib.pyplot as plt x = range(1, 11) y = [i**2 for i in x] plt.plot(x, y) plt.show()

This returns the following image:

Loading a Sample Matplotlib Plot

Let’s break down what we did here:

  1. We loaded the pyplot module as plt
  2. We defined x values as the values from 1 through 10
  3. We then used a Python list comprehension to define the y values as the square of each x value
  4. We then passed these variables into the plt.plot() function
  5. Finally, we used the .show() method to display the visualization

Changing Plot Size in Matplotlib Using figsize

One of the simplest and most expressive ways of changing the plot size in Matplotlib is to use the figsize= argument. As the name of the argument indicates, this is applied to a Matplotlib figure. Because of this, we first need to instantiate a figure in which to host our plot.

Let’s take a look at how we can do this:

# Changing the figure size using figsize= import matplotlib.pyplot as plt x = range(1, 11) y = [i**2 for i in x] plt.figure(figsize=(5, 5)) plt.plot(x, y) plt.show()

This returns the following image:

Using figsize to Change Matplotlib Figure Size

In the code above, we accessed the Figure that was created by default. In the code above, we assigned the figsize= parameter in order to specify the size of the figure we want to use. We passed in a tuple containing the width and the length in inches.

If you’re more accustomed to working with centimeters, you first need to convert the measurement to centimeters. This can be done by multiplying a value in inches by 2.54 to calculate it in centimeters.

Setting the DPI of a Matplotlib Figure

Matplotlib allows you to prepare print-friendly reports. In order to finely tune your printable reports, you can also control the DPI of the charts your produce. By default, Matplotlib uses a DPI of 100 pixels per inch. In order to mofidy this, you can use the dpi= parameter on the figure object.

Let’s change our DPI to 200 pixels per inch:

# Changing the DPI of a Matplotlib Chart import matplotlib.pyplot as plt x = range(1, 11) y = [i**2 for i in x] plt.figure(figsize=(5, 5), dpi=200) plt.plot(x, y) plt.show()

This returns the following image:

Читайте также:  Нормальный алгоритм маркова python

Changing the DPI of a Matplotlib Figure

In the next section, you’ll learn how to use Matplotlib to set width and height individually.

Changing Plot Size in Matplotlib Using set_figheight and set_figwidth

Matplotlib also provides ways to more explicitly define the height and width individually, using the set_fightheight() and set_figwidth() functions. While the previous section showed you how to change the size in one argument, these functions give you the control to modify these parameters individually.

Let’s see how we can use these functions to modify the size of our plot in Matplotlib:

# Using Figure Functions to Change Matplotlib Chart Size import matplotlib.pyplot as plt x = range(1, 11) y = [i**2 for i in x] # Create a figure fig = plt.figure() # Set the width and height fig.set_figwidth(4) fig.set_figheight(6) # Create an axes ax = fig.add_subplot(1, 1, 1) ax.plot(x, y) plt.show()

This returns the following image:

Using fig_setheight and fig_setwidth to change matplotlib size

Let’s break down what we did here:

  1. We declared a figure object
  2. We then used the set_figwidth() and set_figheight() functions to control the figure size
  3. We then declared a subplot axes and added our plot

In the next section, you’ll learn how to use the rcParams in Matplotlib to change plot sizes.

Changing Plot Size in Matplotlib Using rcParams

We can change the figure size in Matplotlib globally using the rcParams available. This allows you to produce multiple visualizations and only modify the size a single time. This can be very valuable when you want to generate multiple plots and need them all to be the same size.

Let’s see how we can use rcParams to control the figure size in Matplotlib:

# Using rcParams to Change Figure Size in Matplotlib import matplotlib.pyplot as plt x = range(1, 11) y = [i**2 for i in x] plt.rcParams['figure.figsize'] = (8, 4) plt.plot(x, y) plt.show()

This returns the following image:

Using rcParams to Change Figure Size in Matplotlib

In the code above, we accessed the rcParams dictionary key for figure.figsize in order to pass in a tuple that contained the width and height of the figure.

Conclusion

In this tutorial, you learned how to change the figure size of a Matplotlib plot. You learned how to change the size of a plot using the figsize= parameter. Then, you learned how to use the figure object functions, set_figheight() and set_figwidth() functions to change the size of a Matplotlib plot. Finally, you learned how to use rcParams to change the size of a Matplotlib chart. You also learned how to control the DPI of a Matplotlib visualization.

Additional Resources

To learn more about related topics, check out the tutorials below:

Источник

Оцените статью