Подплот из двух графиков в Python не отображается правильно - PullRequest
0 голосов
/ 10 апреля 2020

Я пытаюсь напечатать 2 графика на основе некоторых обучающих данных в Python, но похоже, что подзаговор не работает, он делает меня двумя отдельными фигурами, это не проблема, проблема в том, что второй график это пусто ... Вот мой первый график:

df = pd.read_csv("Boston.csv")
df = pd.DataFrame(
    {"Actual value of medv": y_test, "Predicted": y_pred}
)  
df1 = df.head()
plt.subplot(211)  # here idk why it's not working
# plot the Bar graph showing the comparison of 
#  Actual and Predicted values.
df1.plot(
    kind="bar", figsize=(16, 10)
)  
plt.show()  
# Though my model is not very precise, some predicted 
#  percentages are close to the actual ones.
plt.subplot(212)
# Plot the linear regression line
fig = plt.scatter(X_train, y_train)

# Create a range of points. Compute 
#  yhat=coeff1*x + intercept 
#  and plot the regression line.
x = np.linspace(0, 40, 20)
figura1 = plt.plot(x, linreg.coef_ * x + linreg.intercept_, color="red")
plt.legend(["Regression line", "data"])

Здесь вы можете увидеть, как выглядит мой график прямо сейчас: with subplot on

и вот он с удаление подзаголовков: without subplot

CSV-файл можно найти здесь: https://github.com/tvganesh/MachineLearning-RandPython/blob/master/Boston.csv

Ответы [ 2 ]

1 голос
/ 10 апреля 2020

Matplotlib subplots возвращает массив объектов Axes (если вы запрашиваете несколько вспомогательных участков). Используйте эти объекты Axes, чтобы определить, где должны быть построены данные.

Вот пример, основанный на вашем коде:

import matplotlib.pyplot as plt
import pandas as pd

y_test=[3,4,5]
y_pred=[6,7,8]

df = pd.DataFrame(
    {"Actual value of medv": y_test, "Predicted": y_pred}
)  
df1 = df.head()
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
# plot the Bar graph showing the comparison of 
#  Actual and Predicted values.
df1.plot(
    kind="bar", figsize=(16, 10), ax=ax1
)  
# Though my model is not very precise, some predicted 
#  percentages are close to the actual ones.
# Plot the linear regression line
ax2.scatter([1,2,1], [1,2,3])

# Create a range of points. Compute 
#  yhat=coeff1*x + intercept 
#  and plot the regression line.
ax2.plot([1,2,1], color="red")
plt.legend(["Regression line", "data"])
plt.show()  

Subplots mixing panda and matplotlib

1 голос
/ 10 апреля 2020

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

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


df = pd.DataFrame(
    {
        "reg_x": np.random.randint(0, 40, 100),
        "reg_y": np.random.randint(0, 40, 100),
        "y": np.random.randint(0, 50, 100),
        "x": np.random.randint(1, 3, 100),
    }
)

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(10,7))
df.plot.scatter("reg_x", "reg_y", ax=ax1)
# Mock a regression line
ax1.plot([0,40],[18,22],'g-')
df.plot.bar("x", ax=ax2)

Example of two subplots

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...