Repository: pyqtgraph/pyqtgraph

Issue:
Legend overlaps with plot contents
<!-- In the following, please describe your issue in detail! -->
<!-- If some of the sections do not apply, just remove them. -->

### Short description
<!-- This should summarize the issue. -->
When adding a legend to a plot, the legend and the plot contents overlap. An example out of an application I'm building: 
![image](https://user-images.githubusercontent.com/21220820/83953076-b0266880-a83d-11ea-92c4-d0d14b892821.png)


### Code to reproduce
<!-- Please provide a minimal working example that reproduces the issue in the code block below.
     Ideally, this should be a full example someone else could run without additional setup. -->
```python
import pyqtgraph as pg
import numpy as np

plot = pg.plot().getPlotItem()
plot.addLegend()

x = np.arange(50)
y = np.cos(x / 100) * 3
item = pg.BarGraphItem(x=x, height=y, width=0.8, pen="w")

plot.addItem(item)
plot.legend.addItem(item, 'bar')

input("Press enter to quit")
```

### Expected behavior
I could imagine multiple possible fixes:

1. Make the legend opaque
2. Automatically zoom out a little to make space for the legend

### Real behavior
The legend simply appears on the top left, without any consideration whether it overlaps with the plot.

### Tested environment(s)

 * PyQtGraph version: 0.11.0rc0
 * Qt Python binding: PyQt5 5.14.2 Qt 5.14.2
 * Python version: 3.8.3
 * NumPy version: 1.17.4
 * Operating system: Arch Linux
 * Installation method: pip 


Discussion:
You can specify a brush for the `LegendItem` to have an opaque background:

```python
import pyqtgraph as pg
import numpy as np

win = pg.plot()
plot = win.getPlotItem()
legend = plot.addLegend()
legend.setBrush('k')

x = np.arange(50)
y = np.cos(x / 100) * 3
item = pg.BarGraphItem(x=x, height=y, width=0.8, pen="w")

plot.addItem(item)
plot.legend.addItem(item, 'bar')

pg.mkQApp().exec_()
```

There are a couple actionable items I think:

It's not obvious from the [docs](https://pyqtgraph.readthedocs.io/en/latest/graphicsItems/legenditem.html) that you can do this, so I'd say we should make sure each settable feature of the legend is documented.

It might also be nice for `addLegend` to take `**kwargs` and pass them along to create the `LegendItem` so that you could write `plotitem.addLegend(brush='k')` for convenience.
The invisible default background for legend is btw. new since PR #958, using 0.10 legends have a solid background.
uhhh?
![Screenshot_20200607_001245](https://user-images.githubusercontent.com/21220820/83955478-a0b21a00-a853-11ea-9155-de52968d2a62.png)
Is this another bug or am I using it wrong
Ah, that was fixed by #1139 and didn't make it in 0.11.0rc0
Back to the git version of pyqtgraph I guess. That's better anyway with all the new features. Thanks for the quick response btw
FWIW this is the first issue that's been reported that wasn't addressed by 0.11rc0 I think.

Resolving patch:
diff --git a/pyqtgraph/graphicsItems/LegendItem.py b/pyqtgraph/graphicsItems/LegendItem.py
--- a/pyqtgraph/graphicsItems/LegendItem.py
+++ b/pyqtgraph/graphicsItems/LegendItem.py
@@ -13,10 +13,13 @@
 class LegendItem(GraphicsWidget, GraphicsWidgetAnchor):
     """
     Displays a legend used for describing the contents of a plot.
-    LegendItems are most commonly created by calling PlotItem.addLegend().
 
-    Note that this item should not be added directly to a PlotItem. Instead,
-    Make it a direct descendant of the PlotItem::
+    LegendItems are most commonly created by calling :meth:`PlotItem.addLegend
+    <pyqtgraph.PlotItem.addLegend>`.
+
+    Note that this item should *not* be added directly to a PlotItem (via
+    :meth:`PlotItem.addItem <pyqtgraph.PlotItem.addItem>`). Instead, make it a
+    direct descendant of the PlotItem::
 
         legend.setParentItem(plotItem)
 
@@ -46,8 +49,6 @@ def __init__(self, size=None, offset=None, horSpacing=25, verSpacing=0, pen=None
         ==============  ===============================================================
 
         """
-
-
         GraphicsWidget.__init__(self)
         GraphicsWidgetAnchor.__init__(self)
         self.setFlag(self.ItemIgnoresTransformations)
@@ -71,9 +72,11 @@ def __init__(self, size=None, offset=None, horSpacing=25, verSpacing=0, pen=None
         self.opts.update(kwargs)
 
     def offset(self):
+        """Get the offset position relative to the parent."""
         return self.opts['offset']
 
     def setOffset(self, offset):
+        """Set the offset position relative to the parent."""
         self.opts['offset'] = offset
 
         offset = Point(self.opts['offset'])
@@ -83,13 +86,13 @@ def setOffset(self, offset):
         self.anchor(itemPos=anchor, parentPos=anchor, offset=offset)
 
     def pen(self):
+        """Get the QPen used to draw the border around the legend."""
         return self.opts['pen']
 
     def setPen(self, *args, **kargs):
-        """
-        Sets the pen used to draw lines between points.
-        *pen* can be a QPen or any argument accepted by
-        :func:`pyqtgraph.mkPen() <pyqtgraph.mkPen>`
+        """Set the pen used to draw a border around the legend.
+
+        Accepts the same arguments as :func:`~pyqtgraph.mkPen`.
         """
         pen = fn.mkPen(*args, **kargs)
         self.opts['pen'] = pen
@@ -97,9 +100,14 @@ def setPen(self, *args, **kargs):
         self.update()
 
     def brush(self):
+        """Get the QBrush used to draw the legend background."""
         return self.opts['brush']
 
     def setBrush(self, *args, **kargs):
+        """Set the brush used to draw the legend background.
+
+        Accepts the same arguments as :func:`~pyqtgraph.mkBrush`.
+        """
         brush = fn.mkBrush(*args, **kargs)
         if self.opts['brush'] == brush:
             return
@@ -108,13 +116,13 @@ def setBrush(self, *args, **kargs):
         self.update()
 
     def labelTextColor(self):
+        """Get the QColor used for the item labels."""
         return self.opts['labelTextColor']
 
     def setLabelTextColor(self, *args, **kargs):
-        """
-        Sets the color of the label text.
-        *pen* can be a QPen or any argument accepted by
-        :func:`pyqtgraph.mkColor() <pyqtgraph.mkPen>`
+        """Set the color of the item labels.
+
+        Accepts the same arguments as :func:`~pyqtgraph.mkColor`.
         """
         self.opts['labelTextColor'] = fn.mkColor(*args, **kargs)
         for sample, label in self.items:
@@ -123,6 +131,7 @@ def setLabelTextColor(self, *args, **kargs):
         self.update()
 
     def setParentItem(self, p):
+        """Set the parent."""
         ret = GraphicsWidget.setParentItem(self, p)
         if self.opts['offset'] is not None:
             offset = Point(self.opts['offset'])
@@ -138,10 +147,10 @@ def addItem(self, item, name):
 
         ==============  ========================================================
         **Arguments:**
-        item            A PlotDataItem from which the line and point style
-                        of the item will be determined or an instance of
-                        ItemSample (or a subclass), allowing the item display
-                        to be customized.
+        item            A :class:`~pyqtgraph.PlotDataItem` from which the line
+                        and point style of the item will be determined or an
+                        instance of ItemSample (or a subclass), allowing the
+                        item display to be customized.
         title           The title to display for this item. Simple HTML allowed.
         ==============  ========================================================
         """
@@ -177,7 +186,7 @@ def removeItem(self, item):
                 return                                  # return after first match
 
     def clear(self):
-        """Removes all items from legend."""
+        """Remove all items from the legend."""
         for sample, label in self.items:
             self.layout.removeItem(sample)
             self.layout.removeItem(label)
@@ -185,15 +194,6 @@ def clear(self):
         self.items = []
         self.updateSize()
 
-    def clear(self):
-        """
-        Removes all items from the legend.
-
-        Useful for reusing and dynamically updating charts and their legends.
-        """
-        while self.items != []:
-            self.removeItem(self.items[0][1].text)
-                
     def updateSize(self):
         if self.size is not None:
             return
@@ -234,7 +234,7 @@ def boundingRect(self):
     def paint(self, p, *args):
         opts = self.item.opts
 
-        if opts['antialias']:
+        if opts.get('antialias'):
             p.setRenderHint(p.Antialiasing)
 
         if not isinstance(self.item, ScatterPlotItem):
diff --git a/pyqtgraph/graphicsItems/PlotItem/PlotItem.py b/pyqtgraph/graphicsItems/PlotItem/PlotItem.py
--- a/pyqtgraph/graphicsItems/PlotItem/PlotItem.py
+++ b/pyqtgraph/graphicsItems/PlotItem/PlotItem.py
@@ -682,17 +682,19 @@ def plot(self, *args, **kargs):
         
         return item
 
-    def addLegend(self, size=None, offset=(30, 30)):
+    def addLegend(self, offset=(30, 30), **kwargs):
         """
-        Create a new LegendItem and anchor it over the internal ViewBox.
-        Plots will be automatically displayed in the legend if they
-        are created with the 'name' argument.
+        Create a new :class:`~pyqtgraph.LegendItem` and anchor it over the
+        internal ViewBox. Plots will be automatically displayed in the legend
+        if they are created with the 'name' argument.
 
         If a LegendItem has already been created using this method, that
         item will be returned rather than creating a new one.
+
+        Accepts the same arguments as :meth:`~pyqtgraph.LegendItem`.
         """
         if self.legend is None:
-            self.legend = LegendItem(size, offset)
+            self.legend = LegendItem(offset=offset, **kwargs)
             self.legend.setParentItem(self.vb)
         return self.legend
         


Test patch: